ZachLabs Arduino

Lab 13: Ultrasonic Rangefinder

The ultrasonic rangefinder in your kit uses ultrasonic sound (sound frequencies that are too high to be heard by humans) to measure the distance to the nearest obstacle and convert it into a signal that can be read by a microcontroller. This is similar to how bats use echolocation to “see” in the dark.

Example Program

Connect the ultrasonic rangefinder to your Arduino by making the following connections with the long M-to-F jumper wires included in your kit, and then upload the program to your Arduino:

Ultrasonic Rangefinder Arduino Pin
Vcc 5V
Trig 2
Echo 3
Gnd GND
long readDistance(int trigPin, int echoPin)
{
    // Pulse the TRIG pin for 10 microseconds:
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    // Measure the length of the pulse on the ECHO pin with a 24 ms timeout:
    return pulseIn(echoPin, HIGH, 24000);
}

void setup() 
{
    Serial.begin(9600);
    pinMode(2, OUTPUT);
    pinMode(3, INPUT);
}

void loop() 
{
    Serial.println(readDistance(2, 3));
}

If you open the serial monitor in the Arduino IDE you should see a stream of numbers being printed to the screen that get lower the closer you move an obstacle (like your hand or a book) to the front of the ultrasonic rangefinder.

Learn More

Assignment

Create a "personal space detector" with the ultrasonic rangefinder and three LEDs (green, yellow, and red) that is normally green but switches to yellow when someone walks within 2 meters of the sensor and red when someone walks within 1 meter of the sensor. Remember that measurements of 0 indicate an error and should be ignored. If your lights flicker too much, try adding a delay between successful measurements.

The readDistance() function returns the total time, in µs, for the ultrasonic sound to leave the rangefinder's speaker, bounce off the target, and return to the rangefinder's microphone. Although the speed of sound varies based on temperature and humidity, we can assume a standard speed of 343 m/s. This means that a measurement of 1000 µs corresponds to a total travel distance of 34.3 cm (to the target and back), or a distance to the target of 17.15 cm (half the total travel distance).