Ultrasonic module-measuring distance (TIM)

The tutorial mainly demonstrates the implementation of the ultrasonic module distance measurement function.

Hardware connection

image-20240825211022559

Just install it to the corresponding interface:

Ultrasonic moduleSTM32F103RCT6
VCC5V
TRIGPA0
ECHOPA1
GNDGND

Control principle

image-20240903172307044

Trigger ranging signal

The TRIG pin sends a high level signal for more than 10us.

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

Distance=ThighVspeed2

Pin definition

Main control chipPinMain function (after reset)Default multiplexing functionRedefine function
STM32F103RCT6PA0PA0WKUP/USART2_CTS/ADC123_IN0/TIM2_CH1_ETR/TIM5_CH1/TIM8_ETR 
STM32F103RCT6PA1PA1USART2_RTS/ADC123_IN1/TIM5_CH2/TIM2_CH2 

Software code

Since the default function of all pins is the ordinary IO pin function, we need to use the multiplexing function.

Control function

The tutorial only briefly introduces the code, you can open the project source code to read it in detail.

ultrasonic_init

TIM2_Cap_Init

TIM2_IRQHandler

Experimental phenomenon

The Ultrasonic.hex file generated by the project compilation is located in the OBJ folder of Ultrasonic project. The corresponding Ultrasonic.hex file is found and the program is downloaded into the development board by using FlyMcu software.

After successful download: Serial port will print Ultrasonic Class! After hardware initialization Then control LED status switch and print obstacle distance every 500ms.

image-20240808192926663