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.
Wiring is easy: read the labels provided on the device and wire to the Arduino as follows:
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.
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.