HC-SR04 Ultrasonic Ranger – Part 1

Figure 1 - In Action

First go with a HC-SR04 Ultrasonice Range Finder with an Arduino Nano.  Very simple, worked out of the box.  Connected it up, downloaded the New Ping Library for Arduino, used the example program and off it went.

Below I’ll include the schematic & example program.  Will need to have a go at some practical uses for this next.

Figure 2 below shows the schematic.

Figure 2 - Schematic

Below is the example program that was included with the New Ping library.

#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.
//The setup function is called once at startup of the sketch
void setup()
{
	  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

// The loop function is called in an endless loop
void loop()
{
	  delay(50);                      // Wait 50ms between pings (about 20 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");
}

Leave a Reply

Your email address will not be published. Required fields are marked *