1
Ultrasonic distance measurement
Used sensor: HC-SR04
Connections 8example):
Vcc - +5V
GND
Trig ← Arduino pin 12
Echo → Arduino pin 11
Sample Arduino code
#define trigPin 12
#define echoPin 11
long duration;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
digitalWrite(trigPin, 0);
}
void loop() {
Serial.println(get_distance());
delay(500);
}
long get_distance(void){
// get distance in mm
long duration;
duration = read_sr04();
return (duration * 343)/2000;
}
long read_sr04(void){
// get echo time in us
digitalWrite(trigPin, 1);
delayMicroseconds(10);
digitalWrite(trigPin, 0);
return pulseIn(echoPin, 1);
}
The function read_sr04() puts a trigger pulse of 10μs length to the trigger pin and waits for a
response pulse. The distance is coded in the pulse length of this pulse. The pulse length is measured
with the pulseIn function.
v⋅t
To calculate the distance, this has to be converted: d=
2
2
The division by 2 takes into account that the sound wave has to travel twice the distance.
Sample oscillogramme for d=5cm:
pulse length: 293us
The ultrasonic wave propagates with approximately v=340m/s, it has to travel the distance d two
times.
v⋅t
So we have d= ≃0.048 m which is correct.
2
How accurate will the measuring be?
v 343 m/s
The wave length can be calculated to λ= = =8.6 mm
f 40⋅103 Hz
The accuracy will not be better than a half wavelength, that is to say about 4mm.
There are some other influencies.
The sonic beam has a parallax error, due to the sender and receiver distance of about 25mm. This
will lead to values that are too big for very short distances.
The air temperature has an impact on the sonic velocity: v ≃20⋅ (
√ T m
)
K s
This gives a variation of 318 to 353 m/s when the temperature variates from -20°C to +40°C, a
variation of about 10%.
3
Measured values for an object 150 x 80mm in front of the sensor:
For distances >20mm the measured error is about 0..+10mm.
According to the datasheet the maximum range should be 4m.
How narrow is the focus?
The datasheets states an angle of 15°.
I tried to test this experimentally by approaching an object from sideways to the ultrasonic beam.
When the object was detected, the measured value jumped from big to small, the distance of the
object.
The angle of 15° was experimentally confirmed.
This relatively sharp angle would allow to build a sort of ultrasonic radar for robots.