Sensors: Ultrasonic Range Finder
In yet another shipment from Deal Extreme, I picked up a HC-SR04 Ultrasonic Range Finder. It seems to be a widely used and supported component, as there are plenty of posts around, and several supporting libraries for Arduino. Usage was also dead simple, and accuracy and responsiveness is good. One data sheet claims 2 - 500 cm ranging distance, at a 0.3 cm resolution, while another mentioned only 4 meters. The results I've gotten seems to be in line with that.
Following Jax' post, and downloading the small ITead Studio library, it was up and running at once. The Arudino sketch is no more than init and read in a loop:
#include "Ultrasonic.h"
Ultrasonic ultrasonic(12,13);
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print(ultrasonic.Ranging(CM));
Serial.println(" cm");
delay(100);
}
The only problem I sometimes detected, is that it will not always handle a sudden change in distance very well. Or possibly not detect the echo signal if facing a distant surface at a slight angle. However, even so, I find that it fails gracefully. The Ranging function above will output a "out of bounds" number (around 2400 cm) when it cannot detect an echo. It means there is a very clear boundary between valid readings at 2 - 400 cm and "failure code" at ~2400.
The next step, is now to mount this on to the model helicopter I just got, and see what we can get from there. Initially as a separate and independent payload, I assume, but maybe later integrated with the main control board for the motors.
For completeness, I'm including the two functions in the library above. As mentioned, it's simple, and just implementing the timing functions described in the above data sheet.
long Timing() {
digitalWrite(Trig_pin, LOW); delayMicroseconds(2);
digitalWrite(Trig_pin, HIGH); delayMicroseconds(10);
digitalWrite(Trig_pin, LOW);
long duration = pulseIn(Echo_pin, HIGH);
return duration;
}
long Ranging(int cm) {
long duration = Timing();
if (cm) {
return duration / 29 / 2;
else {
return duration / 74 / 2;
}
}
On a related note, there are plenty of range finders around, rated for different ranges and resolutions. Sparkfun has the Maxbotix ultrasonic line, as well as the commonly used Sharp IR Proximity sensors. The later are available in a wide range, from several retailers.