ESP8266 - Ultrasonic Sensor

This tutorial instructs you how to use ESP8266 and ultrasonic sensor to measure the distance to obstacles or objects. In detail, we will learn:

Hardware Preparation

1×ESP8266 NodeMCU
1×Micro USB Cable
1×Ultrasonic Sensor
1×Jumper Wires
1×(Optional) 5V Power Adapter for ESP8266
1×(Optional) ESP8266 Screw Terminal Adapter

Or you can buy the following sensor kit:

1×DIYables Sensor Kit 30 types, 69 units
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you. We appreciate your support.

Overview of Ultrasonic Sensor

The HC-SR04 ultrasonic sensor is used to ascertain the distance to an object through the use of ultrasonic waves.

The Ultrasonic Sensor Pinout

The HC-SR04 ultrasonic sensor has four pins:

  • VCC pin: must be connected to VCC (5V)
  • GND pin: must be connected to GND (0V)
  • TRIG pin: this pin is where the control signal (pulse) from ESP8266 is received.
  • ECHO pin: this pin sends a signal (pulse) to ESP8266. ESP8266 measures the length of the pulse to calculate the distance.
Ultrasonic Sensor pinout

How It Works

This section includes advanced information that may be overwhelming. If you are unsure about the content, feel free to skip it and move on to the next sections.
  1. The micro-controller produces a 10-microsecond pulse on the TRIG pin, which triggers the ultrasonic sensor to emit ultrasonic waves.
  2. The ultrasonic wave is reflected after hitting an obstacle.
  3. The ultrasonic sensor then detects the reflected ultrasonic wave and measures its travel time.
  4. The ultrasonic sensor generates a pulse to the ECHO pin, with the pulse duration being equal to the travel time of the ultrasonic wave.
  5. The micro-controller measures the pulse duration in the ECHO pin and calculates the distance between the sensor and the obstacle.

How to Get Distance From Ultrasonic Sensor

  1. To calculate the distance from the ultrasonic sensor, two steps must be taken (1 and 6 on How It Works section):
  2. Generate a 10-microsecond pulse on the TRIG pin.
  3. Measure the pulse duration in the ECHO pin.
  4. Calculate the distance between the sensor and obstacle.

Distance Calculation

We have:

  • The travel time of the ultrasonic wave (µs): travel_time = pulse_duration
  • The speed of the ultrasonic wave: speed = SPEED_OF_SOUND = 340 m/s = 0.034 cm/µs

So:

  • The travel distance of the ultrasonic wave (cm): travel_distance = speed × travel_time = 0.034 × pulse_duration
  • The distance between sensor and obstacle (cm): distance = travel_distance / 2 = 0.034 × pulse_duration / 2 = 0.017 × pulse_duration

ESP8266 - Ultrasonic Sensor

We can use two pins of an ESP8266 to measure the distance from an ultrasonic sensor: One pin is connected to the TRIG pin to generate a 10µs pulse, and the other pin is connected to the ECHO pin to measure the pulse from the sensor.

Wiring Diagram

The wiring diagram between ESP8266 NodeMCU and Ultrasonic Sensor

This image is created using Fritzing. Click to enlarge image

See more in ESP8266's pinout and how to supply power to the ESP8266 and other components.

How To Program For Ultrasonic Sensor

  • Generate a 10-microsecond pulse on ESP8266's pin D5 by utilizing the digitalWrite() and delayMicroseconds() functions. For example:
  • Set the pin to HIGH with digitalWrite(), then delay for 10 microseconds with delayMicroseconds(), then set the pin to LOW with digitalWrite().
digitalWrite(D5, HIGH); delayMicroseconds(10); digitalWrite(D5, LOW);
  • Measure the pulse duration (µs) on Arduino's pin D6 by utilizing the pulseIn() function. For example:
duration_us = pulseIn(D6, HIGH);
  • Calculate the distance (cm):
distance_cm = 0.017 * duration_us;

ESP8266 Code

const int TRIG_PIN = D5; // The ESP8266 pin D5 connected to Ultrasonic Sensor's TRIG pin const int ECHO_PIN = D6; // The ESP8266 pin D6 connected to Ultrasonic Sensor's ECHO pin float duration_us, distance_cm; void setup() { // begin serial port Serial.begin (9600); // Configure the trigger pin to output mode pinMode(TRIG_PIN, OUTPUT); // Configure the echo pin to input mode pinMode(ECHO_PIN, INPUT); } void loop() { // Produce a 10-microsecond pulse to the TRIG pin. digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // Measure the pulse duration from the ECHO pin duration_us = pulseIn(ECHO_PIN, HIGH); // calculate the distance distance_cm = 0.017 * duration_us; // print the value to Serial Monitor Serial.print("distance: "); Serial.print(distance_cm); Serial.println(" cm"); delay(500); }

Detailed Instructions

To get started with ESP8266 on Arduino IDE, follow these steps:

  • Check out the how to setup environment for ESP8266 on Arduino IDE tutorial if this is your first time using ESP8266.
  • Wire the components as shown in the diagram.
  • Connect the ESP8266 board to your computer using a USB cable.
  • Open Arduino IDE on your computer.
  • Choose the correct ESP8266 board, such as (e.g. NodeMCU 1.0 (ESP-12E Module)), and its respective COM port.
  • Copy the code and open it in Arduino IDE.
  • Click the Upload button on Arduino IDE to compile and upload the code to ESP8266.
How to upload code to ESP8266 NodeMCU using Arduino IDE
  • Open the Serial Monitor
  • Move your hand in the vicinity of the ultrasonic sensor
  • Check out the distance between the sensor and your hand displayed on the Serial Monitor
COM6
Send
distance: 29.4 cm distance: 27.6 cm distance: 26.9 cm distance: 17.4 cm distance: 16.9 cm distance: 14.3 cm distance: 15.6 cm distance: 13.1 cm
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

How to Filter Noise from Distance Measurements of Ultrasonic Sensor

The measurement result from an ultrasonic sensor may include noise, which can lead to unwanted operations in certain applications. To remove the noise, the following algorithm can be used:

  1. Take multiple measurements and store them in an array
  2. Sort the array in ascending order
  3. Filter out the noise
    • Some of the smallest samples are considered as noise → ignore them
    • Some of the largest samples are considered as noise → ignore them
    • Calculate the average of the middle samples

    The below example code takes 20 measurements:

    • The five smallest samples should be disregarded.
    • The five largest samples should be disregarded.
    • The average of the 10 middle samples (from 5th to 14th) should be taken.
    /* * This ESP8266 NodeMCU code was developed by newbiely.com * * This ESP8266 NodeMCU code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp8266/esp8266-ultrasonic-sensor */ #define TRIG_PIN D5 // The ESP8266 pin connected to Ultrasonic Sensor's TRIG pin #define ECHO_PIN D6 // The ESP8266 pin connected to Ultrasonic Sensor's ECHO pin float filterArray[20]; // array to store data samples from sensor float distance; // store the distance from sensor void setup() { // begin serial port Serial.begin (9600); // Configure the trigger and echo pins to output mode pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); } void loop() { // 1. TAKING MULTIPLE MEASUREMENTS AND STORE IN AN ARRAY for (int sample = 0; sample < 20; sample++) { filterArray[sample] = ultrasonicMeasure(); delay(30); // to avoid untrasonic interfering } // 2. SORTING THE ARRAY IN ASCENDING ORDER for (int i = 0; i < 19; i++) { for (int j = i + 1; j < 20; j++) { if (filterArray[i] > filterArray[j]) { float swap = filterArray[i]; filterArray[i] = filterArray[j]; filterArray[j] = swap; } } } // 3. FILTERING NOISE // + the five smallest samples are considered as noise -> ignore it // + the five biggest samples are considered as noise -> ignore it // ---------------------------------------------------------------- // => get average of the 10 middle samples (from 5th to 14th) double sum = 0; for (int sample = 5; sample < 15; sample++) { sum += filterArray[sample]; } distance = sum / 10; // print the value to Serial Monitor Serial.print("distance: "); Serial.print(distance); Serial.println(" cm"); } float ultrasonicMeasure() { // Produce a 10-microsecond pulse to the TRIG pin. digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // Measure the pulse duration from the ECHO pin float duration_us = pulseIn(ECHO_PIN, HIGH); // calculate the distance float distance_cm = 0.017 * duration_us; return distance_cm; }

Video Tutorial

Challenge Yourself

Employ an ultrasonic sensor for any of the following projects:

  • Construct a collision avoidance system for a remote-controlled car.
  • Estimate the fullness of a dustbin.
  • Monitor the level of a dustbin.
  • Automate the opening and closing of a dustbin. Hint: See ESP8266 - Servo Motor.

Ultrasonic Sensor Applications

  • Prevention of Collisions
  • Estimation of Capacity
  • Estimation of Height
  • Identification of Nearby Objects

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!