Ultrasonic ranging module HC – SR04 provides 2cm – 400cm non-contact measurement function, the ranging accuracy can reach to 3mm. The modules includes ultrasonic transmitters, receiver and control circuit.
Today in this tutorial we are going to learn How to interface HC-SR04 Ultrasonic sensor module with STM32.
Working of hcsr04 is pretty simple and straight.
The module emits an ultrasound at 40 KHz which, after reflecting from obstacle, bounces back to the module. By using the travel time and the speed of the sound, we can calculate the distance between the sensor and the obstacle.
According to the datasheet of hc-sr04, the following is required to be done :-
- Keep the pin HIGH for at least 10us
- The Module will now send 8 cycle burst of ultrasound at 40 kHz and detect whether there is a pulse signal back
- IF the signal returns, module will output a HIGH PULSE whose width will be proportional to the range of the object.
- Distance can be calculated by using the following formula :- range = high level time * velocity (340m/s) / 2
- We can also use uS / 58 = Distance in cm or uS / 148 = distance in inch
- It is recommended to wait for at least 60ms before starting the operation again.
|You can download the full code at the end of the post|
uint32_t local_time, sensor_time;
uint32_t hcsr04_read (void)
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET); // pull the TRIG pin HIGH
DWT_Delay_us(2); // wait for 2 us
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_SET); // pull the TRIG pin HIGH
DWT_Delay_us(10); // wait for 10 us
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET); // pull the TRIG pin low
// read the time for which the pin is high
while (!(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_2))); // wait for the ECHO pin to go high
while (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_2)) // while the pin is high
local_time++; // measure time for which the pin is high
sensor_time = hcsr04_read();
distance = sensor_time * .034/2;
lcd_send_string ("Dist= ");
lcd_send_string (" cm");
|You can check out the Video below|