The HC-SR04 is an ultrasound distance sensor that is very easy to control and is available at an affordable price. The working principle is quite simple: Similar to sonar, the sensor emits a sound pulse that travels from the sensor and may be reflected by an object. The sound travels from the sensor to the object, gets reflected there, and returns to the sensor as an echo. The sensor has built-in signal processing that immediately displays any detected echoes. The time it takes for the echo to be received is also known as the time of flight. By measuring this time with the Arduino, you can calculate the distance using the speed of sound.
The sensor is controlled as follows: When there is a falling edge on the trigger input of the sensor, which must last longer than 10µs, the transmission of an ultrasound signal is prepared. Once this signal has been transmitted, the echo pin switches from LOW to HIGH. When the echo of the ultrasound pulse is received, the echo pin returns to LOW. For distance measurement, you only need to measure the time during which the echo pin remains HIGH, and then convert that time into distance.
Here is the wiring diagram:
Thanks to the standard libraries provided with the Arduino, the code is also straightforward to write.
//******************* // Distance HC-SR04 // Madgyver.de //******************* #define echopin 12 #define triggerpin 13 #define speedfactor 29.41/2 //half of the time for Microseconds needed for one centimeter void setup() { Serial.begin(9600); pinMode(triggerpin, OUTPUT); pinMode(echopin, INPUT); } void loop() { Serial.println(measure() / speedfactor); delay (10); } int measure() { int duration = 0; //sending start condition digitalWrite(triggerpin, HIGH); delayMicroseconds(10); digitalWrite(triggerpin, LOW); //measure time of flight in microseconds duration = pulseIn(echopin, HIGH, 10000); //10ms timeout return duration; }
The code does exactly what was described earlier, so I will only focus on the conversion. The function “measure” gives us a value that corresponds to the time until the echo is received. The value is given in microseconds. The conversion factor is calculated as follows:
- Sound travels at a speed of about 340m/s at normal room temperatures.
- The reciprocal of this is 0.00294117647s/m, which is the time sound takes to travel one meter.
- Multiplying by 1000000 gives the same time in microseconds: 2941.17647µs/m.
- In centimeters, this is approximately 29.41µs/cm.
- Since the signal travels to the object and back, we need to consider this as well.