Reading an ultrasonic ranger: how far is it?

An ultrasonic ranger sends out an ultrasonic (roughly 40,000Hz) chirp and listens for an echo; it then reports back how long the echo took to return, and you can do some easy math to figure out the distance between the ranger and the surface the sound is bouncing off of.

These devices are quite inexpensive and quite easy to use. They are probably also very annoying to nearby dogs, dolphins, and bats.

The circuit

../_images/ultrasonicRangerSchematic.png

Wiring is easy: read the labels provided on the device and wire to the Arduino as follows:

  • VCC: +5V
  • trigger and echo are data pins which connect with the pins as described in the sketch
  • GND: ground

The ultrasonic ranger, like most small simple digital devices that are Arduino inputs, does not use much current and so it’s fine to run off of the Arduino’s 5V supply.

Arduino code to talk to the ultrasonic ranger and print distances via the serial monitor

It’s easiest to talk with this device by using the NewPing “library,” basically a software add-on to the base Arduino program. Begin by searching for the “NewPing” library online, downloading the ZIP, then in the Arduino software use Sketch–>Include library–>Add .ZIP Library. The sketch here is based on NewPingExample.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <NewPing.h>

#define TRIGGER_PIN  12  // attach the trigger pin to Arduino pin 12
#define ECHO_PIN     11  // attach the echo pin to Arduino pin 11
#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); // looks like Servo myservo!

void setup() {
  Serial.begin(115200); // note that this is not 9600, the usual serial rate
}

void loop() {
  delay(50); // Wait 50ms between pings
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // do pinging, return result in centimeters
  Serial.println("cm");
}

Download link for the above code: ultrasonicRanger.ino.