This project demonstrates how to interface an HC-SR04 ultrasonic distance sensor with an STM32F103C6 microcontroller using the Timer Input Capture mode for precise echo pulse measurement.
The HC-SR04 sensor operates by emitting 40 kHz ultrasound pulses and measuring the time-of-flight of the returning echo. By leveraging STM32’s advanced TIM1 input capture, we can measure the echo pulse width accurately, enabling reliable distance calculation. Measurement results are sent to a UART terminal in real-time for monitoring.
Working Principle
- The STM32 sets TRIG High for 10 µs to start a measurement.
- The sensor emits an ultrasonic burst at 40 kHz.
- The ECHO pin goes High and stays High until the echo is received.
- The STM32’s Timer Input Capture measures the High pulse duration.
- Distance is calculated using:
HC-SR04 Pinout
- VCC → +5V supply
- GND → Ground
- TRIG → Input pin to initiate measurement (10 µs pulse)
- ECHO → Output pin, pulse width proportional to distance
- MCU Selection: STM32F103C6 (16 MHz clock)
- GPIO Configuration:
-
PA10 → Output (TRIG)
-
PA8 → Input Capture (ECHO)
- TIM1 Configuration:
-
Channel 1 → Input Capture Direct Mode
-
Prescaler = 16-1
Counter Period = 65535
- UART1 Configuration:
-
Baud Rate = 115200
-
Word Length = 8 bits
-
No parity
- Generate initialization code in STM32CubeIDE.
Key Functions
- Trigger Pulse Generation
-
void HCSR04_Trigger(void);
-
Sends a 10 µs HIGH pulse on TRIG to start measurement.
- Input Capture Callback
-
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim);
-
Captures rising and falling edges of the ECHO pin to compute pulse width.
- Main Loop
-
HCSR04_Trigger();
-
HAL_UART_Transmit(&huart1, (uint8_t*)msg,
-
sprintf(msg, "Distance: %d cm\r\n", Distance), 100);
-
Periodically triggers the sensor and prints measured distance over UART.
Components
- STM32F103C6 microcontroller
- HC-SR04 ultrasonic sensor (or SRF04 equivalent)
- Virtual Terminal (UART, 115200 baud)
Connections
- PA10 → TRIG
- PA8 → ECHO
- PA9 (UART TX) → Virtual Terminal
Steps
- Load the generated .hex file into STM32 in Proteus.
- Adjust the distance parameter in the SRF04/HC-SR04 component.
- Monitor distance output values in the Virtual Terminal.
If you have any questions or suggestions don’t hesitate to leave a comment below
Comments