Welcome to Raspbot repository
5.5 Ultrasonic avoid
1. Learning target
In this course, we will learn how to use ultrasonic module completes obstacle avoidance experiment.
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.
For the Raspbot car, we use 4 TT DC gear motors. They are driven by the AT8236 chip. The driver chip is not directly connected to the Raspberry Pi pins.
Raspberry Pi communicates with STM8 MUC through IIC, and then STM8 MCU drives AT8236 chip to drive the motor.
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.
STM8 is connected to SDA.1, SCL.1 on the Raspberry Pi board.
We have provided a library text dedicated to driving motors and servos --YB_Pcb_Car.py.
The pin comparison table of Raspberry Pi as shown below.
4. About code
Path: /home/pi/Yahboom_project/Raspbot/2.Hardware Control course/5.Ultrasonic avoid/Ultrasonic avoid.ipynb
1) Import time, GPIO and YB_Pcb_Car library
2)Set the GPIO coding mode , define ultrasonic module pin, and define the car class is used to drive motors or servos.
3)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.
4) Define the ultrasonic ranging optimization program to optimize the test results.
5) Define the avoid function to complete the ultrasonic obstacle avoidance function of the car.
6) Call the obstacle avoidance function in loop to complete the obstacle avoidance experiment.
When we click the stop button, we exit the loop, stop the car, and clear the car class and GPIO.
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 the car will move forward, and it will avoid obstacles when it encounters obstacles in front of it.