First Experiences
Today I tried to set up a HC-SR04 ranging shield with my Arduino board. The main principle is easy: The sensor emits short ultrasonic pulses at 40 kHz, that are reflected by the obstacle. These reflections are detected by the receiver and the elapsed time is returned. With the knowledge of the sound velocity one can easily calculate the distance between the sensor and the obstacle.
In more detail, the sensor needs a 5V DC power supply to operate. To start a measurement one has to apply a 10us TTL signal to the trigger pin. Then the transmitter generates 8 ultrasonic pulses at 40kHz. After the reciever detectes the echoed pulses, the elapsed time is returned as the pulse width applied to the signal pin.
For my first tries I used the following setup:
The HC-SR04 is supplied with the 5V DC voltage from the Arduino board. The sensors trigger and signal pins are connected to the Arduinos digital pins 13 and 12 respectively. Since this setup is very simple, the Arduino program is rather self-explanatory and is shown below.
Source Code:
// Define calibration parameters
float v = 0.0343; // velocity of sound at 20 deg celsius in cm / us
float c0 = 0.0; // constant calibration parameter
float c1 = 1.0; // linear calibration parameter
// Define Pins
int pinPing = 13;
int pinSignal = 12;
void setup() {
// Setting Pin-Modes
pinMode(pinPing, OUTPUT);
pinMode(pinSignal, INPUT);
// Initialize serial interface at 9600 bauds
Serial.begin(9600);
// Set initial pin states
digitalWrite(pinPing, LOW);
}
void loop() {
// Declare local fields
long duration;
// Send Ping
delayMicroseconds(2);
digitalWrite(pinPing, HIGH);
delayMicroseconds(10);
digitalWrite(pinPing, LOW);
duration = pulseIn(pinSignal, HIGH);
Serial.println(signalToDistance(duration), DEC);
delay(1000);
}
float signalToDistance(long duration) {
float uncalDist = duration * v / 2.0;
float calDist = c1 * uncalDist + c0;
return calDist;
}
I used a simple book as an obstacle and a metering rule to compare the the actual distance with the one calculated from the board. The boards response is printed to the serial output and can be observed by the Serial Monitor of the Arduino IDE or any application that may read from serial ports. Although the measurement process was pretty stable, it seems that the built-in calibration is not really accurate. For example the book placed in a distance of 50cm (metering rule) generates an output of 40cm. So the next step will be to recalibrate the measurement and implement calibration parameters. The source code above includes this flexibility already.