Ultrasonic Sensor – HC-SR04

 

The HC-SR04 ultrasonic range sensor is a low cost distance sensor. It can measure from 2 cm up 4-5 meters with a 1 cm resolution. The price of the sensor starts at $0.80 USD.

Note! Be aware that usually this sensor requires 5V and thus does not always work with ESP8266-based boards such as NodeMCU and D1 Mini, that usually operates at 3.3V.

Specification

  • Operating voltage: 5V
  • Range: 2 cm – 5 meters
  • Resolution: 1 cm
  • Price: from $0.80 USD

Connection Diagram

Button (KY-004) Arduino NodeMCU / D1 Mini
VCC +5V
Trig Pin D5
Echo Pin D4
GND GND

Note: Include fritzing diagram

Code example

/*
 * Created by: Simon Bøgh
 * Date: Aug. 18. 2016
 * 
 */

/////////////////////////////////
// Ultrasonic Sensor
/////////////////////////////////
// Defines Tirg and Echo pins of the Ultrasonic Sensor
const int trigPin = 5; // D1 on NodeMCU
const int echoPin = 4; // D2 on NodeMCU

// Variables for the duration and the distance
long duration, cm, inches;

/////////////////////////////////
void setup() {
  // Init serial
  Serial.begin(9600);

  /* Distance sensor setup */
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

/////////////////////////////////
void loop() {
  calculateDistance();
  delay(50);
}

// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance() {
  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  // convert the time into a distance
  cm = (duration / 2) / 29.1;
  inches = (duration / 2) / 74;

  if (cm < 500) {
    Serial.print(inches);
    Serial.print(" in, ");
    Serial.print(cm);
    Serial.print(" cm");
    Serial.println();
  } else {
    Serial.println("Distance too far");
  }
}