From 2522567be0de5d41b9a5b918a68546d8fcc85bbb Mon Sep 17 00:00:00 2001 From: rafa Date: Tue, 13 May 2025 12:41:55 +0100 Subject: [PATCH] Create a class to interact with the ultrasonic distance sensor --- code/DistSensor.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 code/DistSensor.cpp diff --git a/code/DistSensor.cpp b/code/DistSensor.cpp new file mode 100644 index 0000000..36ddef5 --- /dev/null +++ b/code/DistSensor.cpp @@ -0,0 +1,45 @@ +#include + +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; + } + +}; \ No newline at end of file