Let’s continue with distance measurement. Your HC-SR04 will measure the distance to an object in front of it – e.g., your hand. The distance in centimeters will then appear in your Serial Monitor.
First, define two constants – the Arduino pins to which you’ve connected the TRIG and ECHO pins of the HC-SR04. You define a constant with const
, in addition to the type. Unlike a variable, the value stored in it cannot be changed elsewhere in the code.
const int trig = 7;
const int echo = 6;
Next, you need two variables. One for the duration between sending and receiving the ultrasonic signal. Your HC-SR04 sends out a signal, which is reflected by an object in front of it and received again by the sensor – you store the elapsed time in the variable duration
.
The second variable distance
is needed to later calculate the distance to the object from the elapsed time – more on this in a moment.
int duration = 0;
int distance = 0;
___STEADY_PAYWALL___
The Setup Function
The setup in the sketch should hold no surprises for you. Here you simply start the Serial Monitor and define the pinMode for trig and echo. You send the ultrasonic signal out through the trig pin (so OUTPUT) – the echo pin then receives it again (so INPUT).
void setup() {
Serial.begin (9600);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}
The Loop
Now it gets exciting. First, you send a signal from the HC-SR04 by setting the trig pin to HIGH for 10ms and then back to LOW.
digitalWrite(trig, HIGH);
delay(10);
digitalWrite(trig, LOW);
Then you measure the time it takes for the signal to return to the echo pin. You do this with the pulseIn()
function. You store the elapsed time in the variable duration
.
duration = pulseIn(echo, HIGH);
Now, you don’t actually want to know the time, but the distance of the object from the sensor. For this, you need a small calculation. The signal (or ultrasonic wave) from the sensor travels through the air at the speed of sound. This speed is 343.2 m/s at room temperature.
For the sensor, however, we need this value in centimeters per microsecond. Converted, that’s 0.03432 cm/µs.
One aspect is still missing: we’re not interested in the entire time span, but only the time until the signal reaches the object. Therefore, simply divide the value in the duration
variable by 2.
The distance is now calculated as half of the duration * the speed of sound in cm/µs.
distance = (duration / 2) * 0.03432;
Finally, output the distance in the Serial Monitor and wait with a small delay until the next measurement:
Serial.print(distance);
Serial.println(" cm");
delay(500);
And that’s it. Load the sketch from the Exercise Files for this lesson onto your Arduino and try out your new distance meter right away!
In the next lesson, you’ll install a piezo alongside the sensor and turn it into an ultrasonic theremin with a bit of code.