The HC-SR04 Ultrasonic Sensor is widely used to measure distance by emitting ultrasonic waves and measuring the time it takes for the echo to return. It works like sonar:
The ESP8266 reads this timing and converts it into centimeters (cm) or inches (in). Ultrasonic sensors are commonly used in robotics, automation, parking sensors, and water level monitoring.
⚠️ Important: The HC-SR04 ECHO pin outputs 5V, but ESP8266 works at 3.3V. Use a voltage divider (2 resistors, e.g., 1k + 2k) or a logic level shifter to protect the ESP8266.
// HC-SR04 Ultrasonic Sensor with ESP8266
#define TRIG_PIN D2 // GPIO5
#define ECHO_PIN D3 // GPIO4
long duration;
int distance;
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Step 1: Clear TRIG pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Step 2: Send 10us pulse
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Step 3: Measure echo time
duration = pulseIn(ECHO_PIN, HIGH);
// Step 4: Convert to distance
distance = duration * 0.034 / 2; // Speed of sound: 343 m/s
// Step 5: Print distance
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(1000);
}
Define TRIG and ECHO pins
#define TRIG_PIN D2
#define ECHO_PIN D3
TRIG sends the pulse, ECHO receives it.
Send 10µs Trigger Pulse
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
This starts the ultrasonic wave.
Measure Echo Duration
duration = pulseIn(ECHO_PIN, HIGH);
Returns the time in microseconds that the echo pin stayed HIGH.
Convert into Distance
distance = duration * 0.034 / 2;
Place an object 10 cm away → Serial Monitor prints:
Distance: 10 cm
Move object further → Distance increases.
Issue | Cause | Solution |
---|---|---|
Always reads 0 | Wrong wiring | Check TRIG/ECHO pins and voltage divider |
Values fluctuate | Noise / unstable supply | Use capacitor across VCC & GND |
ESP8266 resets | ECHO pin gives 5V | Use voltage divider (e.g., 1k + 2k resistors) |
No output in Serial Monitor | Wrong baud rate | Set Serial Monitor to 115200 baud |
No. The ECHO pin outputs 5V, so you must use a voltage divider before connecting to ESP8266.
It can measure 2 cm to 400 cm with good accuracy.
No. Always power it from 5V for reliable operation.
Yes. You can connect an I2C LCD (1602/2004) or send data to ThingSpeak, Blynk, or MQTT for IoT applications.
It has an accuracy of about ±3 mm under ideal conditions.