45 lines
1.1 KiB
C++
45 lines
1.1 KiB
C++
#include <Arduino.h>
|
|
|
|
class DistSensor {
|
|
|
|
private:
|
|
int trig_pin;
|
|
int echo_pin;
|
|
const int ULTRASONIC_CM_FACTOR = 58;
|
|
|
|
void make_measurement(){
|
|
digitalWrite(this->trig_pin, HIGH);
|
|
//delayMicroseconds(10);
|
|
digitalWrite(this->trig_pin, LOW);
|
|
}
|
|
|
|
public:
|
|
int duration;
|
|
float default_distance;
|
|
|
|
DistSensor(int trig_pin, int echo_pin, float default_distance){
|
|
this->trig_pin = trig_pin;
|
|
this->echo_pin = echo_pin;
|
|
this->default_distance = default_distance;
|
|
}
|
|
|
|
void configure_pins(){
|
|
pinMode(this->trig_pin, OUTPUT);
|
|
pinMode(this->echo_pin, INPUT);
|
|
}
|
|
|
|
int get_duration(){
|
|
this->make_measurement();
|
|
this->duration = pulseIn(this->echo_pin, HIGH);
|
|
return this->duration;
|
|
}
|
|
|
|
int get_distance(){
|
|
return get_duration() / this->ULTRASONIC_CM_FACTOR;
|
|
}
|
|
|
|
bool is_in_range(){
|
|
return this->get_distance() < this->default_distance;
|
|
}
|
|
|
|
}; |