Last active
September 8, 2024 22:54
-
-
Save grizmio/5fe328dbcad6311b2d4cec056badf010 to your computer and use it in GitHub Desktop.
DistanceSensorHelper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://registry.platformio.org/platforms/platformio/espressif8266/boards | |
// /homeassistant/esphome/distance_sensor_helper.h | |
#include "esphome.h" | |
// https://esphome.io/components/sensor/custom | |
class DistanceSensorHelper : public PollingComponent, public Sensor { | |
public: | |
int _trigPin; | |
int _echoPin; | |
DistanceSensorHelper(int polling_time) : PollingComponent(polling_time) { | |
ESP_LOGD("custom", "WOOOOOO"); | |
_trigPin = 4; | |
_echoPin = 5; | |
} | |
unsigned long get_duration() { | |
digitalWrite(_trigPin, LOW); | |
delayMicroseconds(2); | |
digitalWrite(_trigPin, HIGH); | |
delayMicroseconds(20); | |
return pulseIn(_echoPin, HIGH); | |
} | |
int get_distance() { | |
unsigned long avg = get_duration(); | |
char i = 0; | |
unsigned long duration; | |
do { | |
duration = get_duration(); | |
ESP_LOGD("custom", "duration: %lu", duration); | |
avg = (avg + duration) / 2; | |
delay(100); | |
i++; | |
} while (i < 3); | |
int distance = avg * 0.038 / 2; // Speed of sound wave divided by 2 (go and back) | |
return distance; | |
} | |
void setup() override { | |
ESP_LOGD("custom", "trigpin: %i", _trigPin); | |
ESP_LOGD("custom", "echoPin: %i", _echoPin); | |
pinMode(_trigPin, OUTPUT); // Sets the trigPin as an OUTPUT | |
pinMode(_echoPin, INPUT); // Sets the echoPin as an INPUT | |
} | |
void update() override { | |
// This will be called very often after setup time. | |
// think of it as the loop() call in Arduino | |
int d = get_distance(); | |
publish_state(d); | |
ESP_LOGD("custom", "Distancia: %i", d); | |
} | |
}; |
Author
grizmio
commented
Sep 8, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment