Measure Distance using ESP8266 & HC SR04

Measure distance

Using the ESP8266 and the HC-SR04 ultrasonic sensor, you can build a precise distance-sensing device.

How it Works:

The HC-SR04 works on the same principle as sonar or echolocation used by bats.

  1. The Trig pin sends out a high-frequency sound pulse.
  2. The sound travels through the air, hits an object, and bounces back.

  3. The Echo pin listens for that return signal.

  4. By measuring the time it took for the sound to return, we can calculate the distance using the speed of sound.

1. Hardware Setup

To get started, connect your sensor to the ESP8266 according to the connection provided below:

HC-SR04 PinESP8266 PinPurpose
VCCVin (5V)Power (Requires 5V for best range)
GNDGND via 10K ohm resistorGround
TrigD7 (GPIO 13)Sends the pulse
EchoD6 (GPIO 12) via 10K ohm resistorReceives the pulse

2. Understanding the Logic

We perform three main tasks in every loop:

  1. The Trigger: It clears the trigPin and then holds it HIGH for 10 microseconds to “fire” the ultrasonic burst.

  2. The Measurement: It uses the pulseIn() function to measure how many microseconds the echoPin stays HIGH.

  3. The Math: Since sound travels at approximately 0.034 cm/µs, we multiply the time by 0.034. We then divide by 2 because the sound traveled to the object and back.

 3. Deployment and Testing

  1. Upload: Copy the code into your Arduino IDE and upload it to your Amica board.

  2. Serial Monitor: Open the Serial Monitor (Tools > Serial Monitor) and set the baud rate to 9600.

  3. Observation: Move your hand or a flat object in front of the sensor. You will see the distance in centimeters updating every 2 seconds.

/* Author: RobozX */
/* Board: ESP8266 Amica */
/* Description: Measure distance using HC-SR04 */

const int trigPin = D7;  //NodeMCU D7
const int echoPin = D6;  //NodeMCU D6

long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT); 
  pinMode(echoPin, INPUT); 
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2); // Delay in Microseconds

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

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance= duration*0.034/2;
  
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
  
  delay(2000);
}