Using Ultrasonic sensor HC-SR04 in 3-wire mode

Hey Pieter

Look here:
https://wiki.seeedstudio.com/Grove-Ultrasonic_Ranger/

Thats a 3-wire Ultra Sonic Sensor. After abit of struggle I finally got a reading into HA using ESPHome and custom sensor. Pin 5 is used.

This is the code used, removed wifi and more:
yaml

esphome:
  name: name
  platform: ESP32
  board: esp-wrover-kit
  includes:
    - Custom_US_sensor.h
  libraries:
    - "Grove Ultrasonic Ranger"

sensor:
- platform: custom
  lambda: |-
    auto my_sensor = new MyCustomSensor();
    App.register_component(my_sensor);
    return {my_sensor};

  sensors:
    name: "My Custom Sensor"
    unit_of_measurement: cm

Custom_US_sensor.h

#include "esphome.h"
#include "Ultrasonic.h"

Ultrasonic ultrasonic(5);

class MyCustomSensor : public PollingComponent, public Sensor {
 public:


  MyCustomSensor() : PollingComponent(15000) { }

  void setup() override {
    
  }

  void update() override {
    int distance = ultrasonic.MeasureInCentimeters();
    publish_state(distance);
  }
};

My plan is to make this a binary sensor. But that is another hurdle to get over.

1 Like