Using the HC-SR04 Ultrasonic Range Sensor with Arduino

//Using the HC-SR04 Ultrasonic Range Sensor with Arduino

Using the HC-SR04 Ultrasonic Range Sensor with an Arduino


Ultrasonic sensor are great for all kind of projects that need distance measurements, avoiding obstacles as examples.

The HC-SR04 are inexpensive and easy to use since we will be using a Library specifically designed for these sensor.


As you can see, we only need 4 connections :  Voltage, Ground, Trigger and Echo.


Using a Library designed for these sensors will make our code short and simple.

We include the library at the beginning of our code, and then by using simple commands we can control the behaviour of the sensor.

Once you have the library, just go ahead and extract it to the Library folder inside your Arduino IDE software folder.  Make sure to restart the IDE software so the library is loaded at startup.

#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(500);  // Wait 500ms between pings (about 2 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int uS =; // Send ping, get ping time in microseconds (uS).
  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance and print result (0 = outside set distance range, no ping echo)

Copy and Paste the above Sketch/Code in your Arduino IDE.

You can download the NewPing Library we used here: NewPing-Library

By | 2018-02-23T17:32:30-05:00 January 10th, 2015|Tutorials|

Leave A Comment