HC-SR04 Ultrasonic Distance Sensor

Written by Luka Kerr on March 9, 2018

This post explains how to use the HC-SR04 ultrasonic sensor with your Arduino board. You first must download the NewPing library. After this go to the Arduino IDE and select Sketch –> Include Library –> Add .ZIP Library and select the NewPing library just downloaded.

Now include the NewPing header file.

#include <NewPing.h>

Next you have to define three constants, these are explained in the comments. The pins used (12, 11) are shown in the Fritzing diagram at the bottom of the page.

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

Next you use the NewPing library to setup these constants.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Next is the setup() function which reads the input stream and outputs it to the serial monitor. To access this, go to the Arduino IDE, select Tools –> Serial Monitor and make sure it is set at 115200 baud.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

Finally the loop() function is executed every 50ms. This sends a ping and gets its distance in cm away from an object.

void loop() {
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
}

In the end this is what your Arduino sketch should look similar to:

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
}

Fritzing Diagram

The wiring for the sensor is shown below:

fritzing