Using Ultrasonic sensor HC-SR04 in 3-wire mode

Is it ok to use this sensor with esphome in 3-wire mode?

I’m thinking it might be ok, having read this paragraph in an online article:

In 3-Wire mode the single I/O pin is used as both an input and as an output. This is possible because there is never a time when both the input and output are being used. By eliminating one I/O pin requirement we can save a connection to our Arduino and use it for something else. It also is useful when using a chip like the ATtiny85 which has a limited number of I/O pins.

My intended example config for using it this way:

  - platform: ultrasonic
    name: "Ultrasonic Sensor"
    # use the same pin for the trigger and echo
    trigger_pin: 26
    echo_pin: 26

I’m not sure what the esphome code looks like and haven’t experimented with this.

Then, if I may also ask a second question: What is the unit provided by the sensor? It’s not quite clear to me from the docs whether it’s m or cm.

Hey Pieter

Look here:

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:

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

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

    name: "My Custom Sensor"
    unit_of_measurement: cm


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

Ultrasonic ultrasonic(5);

class MyCustomSensor : public PollingComponent, public Sensor {

  MyCustomSensor() : PollingComponent(15000) { }

  void setup() override {

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

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

1 Like

Thanks, this is helpful. I didn’t know you could customise it with custom C code (but I’m also not surprised given the quality of this project).

I’ve since decided just to stick to the 4-wire solution because I already had the sensors.

You can create your binary sensor in the YAML from the sensor you now have. This is what I’ve done:

  - platform: template
    name: "Garage Occupied"
    lambda: |-
      if (id(garage_ultrasonic_sensor).state < 1) {
        return true;
      } else {
        return false;

Note: The 1 is one meter.

Thank you for this code! Worked for me! :slight_smile:

1 Like

Thanks a lot for this solution!
Does anyone know why I don’t see correct numbers after the decimal point? For example I get a result 8.00000 cm.