ESP8266 Ultrasonic Sensor Project
The ESP8266 Ultrasonic Sensor project demonstrates how to interface an HC‑SR04‑style ultrasonic sensor with an ESP8266‑based board (such as NodeMCU or Wemos‑D1). The sensor sends high‑frequency sound pulses and measures the time it takes for the echo to return, allowing the ESP8266 to calculate the distance to obstacles or objects. This makes it ideal for obstacle detection, automatic doors, security systems, and simple parking‑distance indicators.
How the Ultrasonic Sensor Works
The HC‑SR04 ultrasonic sensor has two main pins: Trigger (TRIG) and Echo (ECHO). When the ESP8266 sends a 10‑microsecond pulse to the TRIG pin, the sensor emits a short ultrasonic burst. The waves travel through the air, reflect off nearby objects, and return to the sensor. The sensor then sets the ECHO pin HIGH for the same duration as the travel time of the echo. The ESP8266 uses pulseIn() on the ECHO pin to read this time and converts it to a distance using the known speed of sound.
With sound speed of about 340 m/s, the distance in centimeters is calculated as distance = duration * 0.034 / 2 (dividing by 2 because the wave travels to the object and back). Typical reliable range is about 2–400 cm, though performance can be affected by soft surfaces, angle, or air temperature.
Components Needed
- ✓ESP8266 development board (e.g. NodeMCU‑v2 or Wemos‑D1)
- ✓HC‑SR04‑style ultrasonic sensor
- ✓LED (optional, for visual indication)
- ✓Passive buzzer (optional, for audible alarm)
- ✓220 Ω resistor (for LED)
- ✓Jumper Wires
- ✓Breadboard
Circuit Diagram
Circuit Setup
Typical HC‑SR04 connections to ESP8266 (NodeMCU‑style GPIOs):
- ✓VCC → 5 V on the ESP8266 (HC‑SR04 usually expects 5 V).
- ✓GND → GND on the ESP8266.
- ✓TRIG → D6 (GPIO 12) on ESP8266.
- ✓ECHO → D7 (GPIO 13) on ESP8266.
Ensure a common ground between the sensor and the ESP8266 so the ECHO pin’s logic level is correctly read by the microcontroller. Avoid long power lines and noisy power sources that can disturb the sensor operation.
- ✓LED: Connect an LED anode to GPIO 5 (D1 on NodeMCU) through a 220 Ω resistor; connect the cathode to GND. Use it to indicate when an object is within a set distance.
- ✓Buzzer: Connect the buzzer positive to GPIO 4 (D2 on NodeMCU) and negative to GND for an audible alarm when objects are detected nearby.
Instructions
Configure the Arduino IDE for ESP8266 (e.g. board: NodeMCU‑v2). Initialize serial communication (115200 or 9600 baud) for debugging and define the trigger and echo pins. Set the trigger pin as OUTPUT and the echo pin as INPUT in setup().
In the loop() function, first send a 10‑µs HIGH pulse to the trigger pin, then call pulseIn(echoPin, HIGH) to get the echo time. Convert this value into distance in centimeters (or inches) using the formula and print the result to the Serial Monitor.
Add a simple threshold (for example, 30 cm) to decide when an object is “too close.” If the measured distance is below this threshold, turn on the LED and/or buzzer; otherwise, keep them off. This logic is the core of an obstacle‑detection or parking‑assistance system.
Use a stable 5 V supply for the ultrasonic sensor, especially if connecting several sensors or additional peripherals. Avoid placing the sensor in front of soft, deeply angled, or very small objects that can absorb or scatter the ultrasound. Keep the sensor clean and free from dust or direct water splashes to maintain accuracy.
C++ Example Code (ESP8266 Ultrasonic Sensor with Obstacle Detection)
#include <ESP8266WiFi.h>
// Replace with your Wi‑Fi credentials (if using Wi‑Fi alerts)const char* ssid = "YOUR_WIFI_SSID";const char* password = "YOUR_WIFI_PASSWORD";
// Sensor pins (NodeMCU‑style)const int trigPin = 12; // D6const int echoPin = 13; // D7const int ledPin = 5; // D1 (LED)const int buzzerPin = 4; // D2 (buzzer)
// Define sound speed and threshold#define SOUND_VELOCITY 0.034 // cm/µsconst int closeThreshold = 30; // cm (too close)
// Variables for distancelong duration;float distanceCm;
void setup() { Serial.begin(115200); // Optional: connect to Wi‑Fi // WiFi.begin(ssid, password); // while (WiFi.status() != WL_CONNECTED) delay(1000); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(ledPin, OUTPUT); pinMode(buzzerPin, OUTPUT); digitalWrite(ledPin, LOW); digitalWrite(buzzerPin, LOW); Serial.println("=== ESP8266 ULTRASONIC SENSOR READY ===");}
void loop() { // Clear the trigger digitalWrite(trigPin, LOW); delayMicroseconds(2); // Send 10 µs HIGH pulse to trigger digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the echo pin duration = pulseIn(echoPin, HIGH); // Convert to distance in cm distanceCm = duration * SOUND_VELOCITY / 2.0; // Optional: convert to inches // float distanceInch = distanceCm * 0.3937; // Print to Serial Monitor Serial.print("Distance: "); Serial.print(distanceCm); Serial.println(" cm"); // Obstacle detection logic if (distanceCm <= closeThreshold && distanceCm >= 2) { // Too close digitalWrite(ledPin, HIGH); digitalWrite(buzzerPin, HIGH); Serial.println("OBSTACLE DETECTED!"); // Optional: send Wi‑Fi alert here (HTTP/MQTT) } else { digitalWrite(ledPin, LOW); digitalWrite(buzzerPin, LOW); } delay(500);}Applications
Obstacle Detection and Avoidance: Use the sensor in small robots or automatic platforms to detect walls or objects and stop or turn before collision.
Automatic Doors and Security: Mount the sensor near doors or fences to detect approaching people or objects and trigger lights, cameras, or alarms when the distance falls below a set threshold.
Parking and Level Measurement: Deploy the sensor above parking bays or in storage tanks to estimate distance‑to‑object or liquid level and display or log the values for monitoring and automation purposes.
Notes
The ultrasonic sensor does not output a simple digital HIGH/LOW like a PIR or vibration sensor; instead, the ESP8266 must actively send a trigger pulse and then read the duration on the ECHO pin. This gives a continuous distance measurement rather than a binary event, enabling more flexible thresholding and ranges.
Use the Serial Monitor to verify that the measured distance changes as you move your hand or an object closer and farther from the sensor. This helps you calibrate the close threshold and confirm that the LED and buzzer are working as expected.
You can extend this project by connecting the ESP8266 to Wi‑Fi and sending distance values to a cloud dashboard (ThingSpeak, Blynk, or Node‑RED) so that you can watch real‑time distance readings or receive alerts when an object gets too close, even when you are away from the sensor location.