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.
NOTE:- DWT isn’t used anymore in this tutorial. To create delay in microsecond, I am using TIMER. You can check out the How to use timer to create delay in microseconds https://youtu.be/SqC0IhLKJ9o
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.
Some Insight into the CODE
delay function uses TIMER to create delay in microsecond.
YOU CAN DOWNLOAD FULL CODE AT THE END OF THIS POST
hcsr04_read Reads the sensor as mentioned above. It returns the time for which the PULSE was HIGH, and based on this time, we will do the further calculation for the distance.
In the while loop, we will read the HIGH PULSE time, and than use the formula given in the datasheet to calculate the distance in cm.
You can buy me a
coffee sensor 🙂
Or just Download the code below
- Interface LCD 16×2 with STM32 without I2C January 21, 2020
- Interface DS3231 RTC module with STM32 January 13, 2020
- How to use Binary Semaphore in STM32 January 11, 2020
- Managing Multiple UARTs in STM32 December 18, 2019
- Multiplexer 74HC4051 and STM32 December 6, 2019
- Free RTOS Tutorial 2.0 with STM32 November 27, 2019