Description
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.
Today in this tutorial we are going to learn How to interface HC-SR04 Ultrasonic sensor module with STM32.
WORKING
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.
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.
HOW TO
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.
Connection
CODE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
uint32_t local_time, sensor_time;
uint32_t distance;
uint32_t hcsr04_read (void)
{
local_time=0;
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
DWT_Delay_us (1);
}
return local_time*2;
}
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_I2C1_Init();
DWT_Delay_Init ();
lcd_init ();
while (1)
{
sensor_time = hcsr04_read();
distance = sensor_time * .034/2;
lcd_send_cmd (0x80);
lcd_send_string ("Dist= ");
lcd_send_data ((distance/100)+48);
lcd_send_data (((distance%100)/10)+48);
lcd_send_data (((distance%10))+48);
lcd_send_string (" cm");
HAL_Delay(200);
}
}
|
No comments:
Post a Comment