ESP8266 Node MCU & Ultrasonic HC-SR04 [ Accurate measurement ]

ESP8266 Node MCU & Ultrasonic HC-SR04

In this tutorial we are going to used “ESP8266 12E Node MCU with Ultrasonic Sensor Module (HC-SR04)”.

HC-SR04 Is used to measure the distance between 2 CM to 4 Meter With Ranging Accuracy upto 3 Milimeter.

The material required for this tutorial are:-

  1. The Jumpers wires
  2. Arduino Board For (5v) Supply
  3. Ultrasonic Sensor Module
  4. Solderless Bread Board And ESP8266 Module

The working principle of module is very simple.It emittes Ultrasonic sound. Which travel with the air, If any Obstacle comes in the path. It will bounce back from the module.

Consider the travel time speed of the sound by these Formula:-


   The ultrasonic module having 4 pins-

  • GND
  • VCC
  • ECHO



As you can see the interfacing or connection diagram of HC-SR04 With ESP-8266—

To generate the ultrasonic sound we need to send trriger on high state for 10 microsecond. And 8 cycle of sonic burst which will the speed of sound and At the echo pin you will get the double of its number.

The calculation part is as shown –

    Velocity= Distance/Time

If the object is 10cm away from the module,
speed of sound v=340 m/s
v=0.034 cm/us
Distance d=t*0.034/2

Now it’s time to make the code  for this tutorial and here is an example code is given.



We have to find trigger pins and echo pins. In this case there are pin number 5 & 4 on ESP8266 NODE MCU, then we will need long veriables and i have named it “long duration” for travel time which we will be obtain from the  sensor and integer variable for distance in the setup trigger pin is as output and echo pin as an input.To start serial communication for showing the result on serial monitor,we have set the board rate 9600.

In the main program we have to set the trigger pin on low state for just 2 microsecond.                                                  Now for generating ultrasound wave we have to set trigger pin on high state for 10 microsecond.

Using pulsein function,First is echo pin & second we can set either high or of high,pulsein function will wait for being to go high because by bounce sound wave it start timing, it will wait for low when the sound wave will end which will stop the timing.

For getting the distance go to the tool and serial moniter and you will get the output distance.

For more details of component and material purchase you can vist my website

About the author

Abhay Kalmegh

Hey Guys, I’m Abhay Kalmegh, I’m a Electronics hobbyest and digital marketing nut – it’s my career, hobby, and passion.

View all posts


Leave a Reply

Your email address will not be published. Required fields are marked *