← All posts Blog Post

Wiring an Ultrasonic Distance Sensor to ESP8266

Viktoria Builds

Step-by-step guide to connecting the HY-SRF05 sensor to an ESP8266. Covers 5V power, TRIG on D1 and ECHO on D2, plus a sketch that prints live distance to the Serial Monitor.

Watch on YouTube

The HY-SRF05 is a popular ultrasonic distance sensor that works great with the ESP8266. In this guide I will show you exactly how to wire it up and read distance values in real time.

What you need

  • ESP8266 (NodeMCU or any variant)
  • HY-SRF05 ultrasonic sensor
  • Jumper wires

Wiring

The sensor has five pins: VCC, GND, TRIG, ECHO, and OUT. For this setup we only use TRIG and ECHO — that is all you need to measure distance.

  • VCC → 5V
  • GND → GND
  • TRIG → D1
  • ECHO → D2

The sensor performs better at 5V, so power it from the 5V pin rather than 3.3V.

How it works

The sketch sends a short pulse on TRIG, then listens on ECHO for the return signal. The time between send and receive lets us calculate distance using the speed of sound (0.0343 cm per microsecond).

The code

Full source: github.com/viktoriabuilds/esp8266-ultrasonic-sensor

#define TRIG_PIN D1
#define ECHO_PIN D2

long duration;
float distance;

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
}

void loop() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);

  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  duration = pulseIn(ECHO_PIN, HIGH);
  distance = duration * 0.0343 / 2;

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(500);
}

Upload the sketch and open the Serial Monitor at 115200 baud. You will see live distance readings printed every half second.

Common uses

  • Obstacle detection in robots
  • Distance measurement for automation
  • Object detection for IoT projects

Enjoying this tutorial?

Support the channel on Patreon and get early access to projects, build logs, and more.

Support on Patreon →