Operation idea:
Set the trig and echo ports low during initialization , first send a high-level pulse of at least 10 us to the trig (the module automatically sends 8 square waves of 40K ), and then wait to capture the rising edge of the output of the echo port and capture At the same time as the rising edge, turn on the timer to start timing, wait again to capture the falling edge of echo , when the falling edge is caught, read the time of the timer, this is the time for the ultrasonic wave to run in the air, according to the test distance = (high level Time * speed of sound ( 340M/S )) /2 can calculate the distance from the ultrasonic wave to the obstacle.
programming steps
1. Configure the corresponding GPIO , Trig and Echo pins
2. Configure the timer, enable the interrupt, and record the number of interrupts generated
3. Send a high-level signal greater than 10us to the TRIG port of the module . When the echo signal is sent, the Echo terminal shows a high level, and the timer is turned on at this time; when the echo signal is received, the Echo terminal shows a low level. At this time Turn off the timer.
4. Obtain the high level time of Echo , and use the relevant formula to calculate the distance dis = ( high level time * speed of sound ( 340M/S ) )/2 (take the average value to obtain more accurate data)
Green light at normal distance
Red light and buzzer alarm if there is an obstacle
Serial display distance
#include "led.h"
#include "delay.h"
#include "ultrasonsic.h"
#include "sys.h"
#include "lcd.h"
#include "usart.h"
#include "beep.h"
int main(void)
{
float length;
delay_init();
uart_init(115200); //Initialize the serial port, the baud rate is 115200
LED_Init(); //Initialize the LED
BEEP_Init();//Initialize the buzzer
initHcsr04();
LED0 = 1;//Power on the default green light Bright
while(1){ length=Hcsr04GetLength(); //Get the distance printf("dis = %fcm\r\n",length);//Serial port print distance delay_ms(50); if(length < 10){/ / LED0 = 0; LED1 = 1; BEEP = 1; delay_ms(300); }else{ LED0 = 1; LED1 = 0; BEEP = 0; } }
}