Welcome to Raspbot repository
5.4 Ultrasonic ranging
1. Learning target
In this course, we will learn how to use ultrasonic ranging.
2. Principle of experimental
The ultrasonic module is a sensor that uses ultrasonic characteristics to detect the distance. It has two ultrasonic probes for transmitting and receiving ultrasonic waves. The range of measurement is 3-450 cm.
(1) You need to input a high level signal of at least 10us to the Trig pin to trigger the ranging function of the ultrasonic module.
(2) After the ranging function is triggered, the module will automatically send out 8 ultrasonic pulses with 40 kHz and automatically detect whether there is a signal return. This step is done internally by the module.
(3) When the module detects an echo signal, the ECHO pin will output a high level. The high level duration is the time from when the ultrasonic wave is sent to when it returns. You can calculate the distance by using the time function to calculate the high level duration.
Formula: Distance = High level duration * Speed of sound(340M/S)/2.
3. Coding method
In this course, we use BOARD coding method.
According to the hardware interface manual, we see that the ultrasonic Echo and Trig pins are connected to the 18 and 16 pin of the Raspberry Pi board.
The pin comparison table of Raspberry Pi as shown below.
4. About code
Path: /home/pi/Yahboom_project/Raspbot/2.Hardware Control course/4.Ultrasonic ranging
1) Import time and GPIO library
2) Ignore warning
3)Define the pins of the ultrasonic module
4)Set the coding method of the pin, and set the modes of the Echo and Trig pins
5) Define the ultrasonic ranging function
We need to set a high level signal of at least 10us to the TRIG pin of the ultrasonic module to trigger the module's ranging function.
5. Running code
Click the button shown in the figure below to run the program on the Jupyter Lab interface
6. Experimental phenomenon
After the program runs, we can see that distance will be printed on JupyterLab.