Skip to content

Instantly share code, notes, and snippets.

@grizmio
Last active September 8, 2024 22:54
Show Gist options
  • Save grizmio/5fe328dbcad6311b2d4cec056badf010 to your computer and use it in GitHub Desktop.
Save grizmio/5fe328dbcad6311b2d4cec056badf010 to your computer and use it in GitHub Desktop.
DistanceSensorHelper
// 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);
}
};
@grizmio
Copy link
Author

grizmio commented Sep 8, 2024

sensor:
  - platform: uptime
    name: "Tiempo en línea"

  - platform: adc
    pin: A0
    name: "Voltaje del Sensor"
    id: voltaje_sensor
    update_interval: 10s
    accuracy_decimals: 0
    internal: True
    filters:
      - multiply : 1000


  - platform : custom
    lambda: |-
      auto polling_time = 15000;
      auto dsh = new DistanceSensorHelper(polling_time);
      App.register_component(dsh);
      return {dsh};
    
    sensors:
      - name : "Distancia de agua"
        id: porcentaje_agua
        unit_of_measurement : "cm"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment