Using the HC-SR04 Ultrasonic Range Sensor with Arduino

Got Questions? Click here and post them in the Brainy-Bits Forum to get help!

OVERVIEW

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.



SCHEMATIC

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



THE CODE

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 = sonar.ping(); // 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)
  Serial.println("cm");
}



TUTORIAL VIDEO



Download

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

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

Got Questions? Click here and post them in the Brainy-Bits Forum to get help!

Leave a comment

Comments have to be approved before showing up