Welcome to 520 Motor repository
02.Ultrasonic obstacle avoidance
Ultrasonic obstacle avoidance
Ultrasonic obstacle avoidanceHardware connectionDistance measurement principleMain codeProgram flow chartExperimental phenomenon
The tutorial mainly demonstrates the obstacle avoidance function of the balance car combined with the ultrasonic module.
xxxxxxxxxxThe tutorial only introduces the standard library project code
Hardware connection
| Ultrasonic module | STM32F103RCT6 |
|---|---|
| VCC | 5V |
| TRIG | PA0 |
| ECHO | PA1 |
| GND | GND |
Distance measurement principle
The ultrasonic module is mainly responsible for obtaining the distance between the obstacle and the car to achieve the obstacle avoidance function.

Trigger ranging signal
The TRIG pin sends a high level signal for more than 10us.
xxxxxxxxxxThe ultrasonic module will automatically send 8 40KHz square waves and automatically detect whether there is a signal return
Receive echo signal
If there is a signal return, the ECHO pin will output a high level. The duration of the high level is the time from the ultrasonic wave transmission to the return.
Distance conversion
xxxxxxxxxxT: high level time of echo signalV: sound speed (approximately equal to 340m/s)
Main code
The tutorial mainly explains the code for obstacle avoidance. For detailed code, please refer to the corresponding project file.
APP_avoid
Control the direction of the car's movement according to the distance detected by ultrasonic wave.
xvoid APP_avoid(void){if(g_distance<250){Move_X = -10;my_delay(1);Move_X = 0;Move_Z = 400;my_delay(2);}else{Move_X = 15;Move_Z = 0;}}
Judge whether the distance is less than 25cm. If so, perform the backward and rotation actions; if greater than or equal to 25cm, the car moves forward.
Program flow chart
Briefly introduce the process of function implementation:

Experimental phenomenon
Software code
The U_avoid.hex file generated by the project compilation is located in the OBJ folder of the U_avoid project. Find the U_avoid.hex file corresponding to the project and use the FlyMcu software to download the program into the development board.
xxxxxxxxxxProduct supporting materials source code path: Attachment → Source code summary → 4.Balanced_Car_base → 02.U_avoid
Experimental phenomenon
After the program is started, press KEY1 according to the OLED prompt to start the balance car obstacle avoidance function: OLED will display the distance to the obstacle in front and the inclination of the balance car in real time!
The program has voltage detection. If the voltage is less than 9.6V, the low voltage alarm will be triggered and the buzzer will sound.Common situations for triggering voltage alarms:1. The power switch of the development board is not turned on, and only the Type-C data cable is connected for power supply2. The battery pack voltage is lower than 9.6V and needs to be charged in time