The example code for the HC-SR04 can be found in the chapter11/hc-sr04.py file. Please review the source code before proceeding to get a broad understanding of what this file contains.
Place a solid object in front of the HC-SR04 (about 10 cm) and run the code in a terminal. As you move the object nearer or further from the sensor, the distance printed in the terminal will change, as indicated here:
(venv) python hc-sr04.py
Press Control + C to Exit
9.6898cm, 3.8149"
9.7755cm, 3.8486"
10.3342cm, 4.0686"
11.5532cm, 4.5485"
12.3422cm, 4.8591"
...
Let's review the code.
Firstly, we define the TRIG_GPIO and ECHO_GPIO pins on line 1, and the VELOCITY constant for the speed of sound at line 2. We're using 343 meters per second.
Our code is using 343 m/s for the speed of sound, while the datasheet suggests the value 340 m/s. You will also find other HC-SR04 examples and libraries that use slightly different...