45 lines
1.1 KiB
C++
45 lines
1.1 KiB
C++
#include <Arduino.h>
|
|
|
|
class DistSensor {
|
|
|
|
private:
|
|
int trigPin;
|
|
int echoPin;
|
|
const int ULTRASONIC_CM_FACTOR = 58;
|
|
|
|
void make_measurement(){
|
|
digitalWrite(this->trigPin, HIGH);
|
|
delayMicroseconds(10);
|
|
digitalWrite(this->trigPin, LOW);
|
|
}
|
|
|
|
public:
|
|
int duration;
|
|
float default_distance;
|
|
|
|
DistSensor(int trigPin, int echoPin, float default_distance){
|
|
this->trigPin = trigPin;
|
|
this->echoPin = echoPin;
|
|
this->default_distance = default_distance;
|
|
}
|
|
|
|
void configure_pins(){
|
|
pinMode(this->trigPin, OUTPUT);
|
|
pinMode(this->echoPin, INPUT);
|
|
}
|
|
|
|
int get_duration(){
|
|
this->make_measurement();
|
|
this->duration = pulseIn(this->echoPin, 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;
|
|
}
|
|
|
|
}; |