|
實(shí)現(xiàn)的功能:通過(guò)HC-SR04測(cè)得距離障礙物的距離,并通過(guò)串口打印
/**********/
u16 cnt=0;
void Init_SR()//初始化PB5,PB6 PB5控制Trig,PB6感應(yīng)Echo的接收信號(hào)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_5;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_6;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void start()//輸出一個(gè)十微秒的方波,使傳感器發(fā)出超聲波,起始信號(hào)
{
Trig=1;
delay_us(20);
Trig=0;
}
void startim()//打開(kāi)定時(shí)器
{
TIM_SetCounter(TIM3,0);
cnt=0;
TIM_Cmd(TIM3, ENABLE);
}
void TIM3_IRQHandler(void)//定時(shí)器中斷
{
if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET)
{
cnt++;//cnt每加一次,代表定時(shí)一微秒
TIM_ClearITPendingBit(TIM3,TIM_IT_Update);
}
}
u32 GetEchoTimer(void)
{
u32 t = 0;
t = cnt*1000;//得到MS
t += TIM_GetCounter(TIM3);//得到US
TIM3->CNT = 0; //將TIM3計(jì)數(shù)寄存器的計(jì)數(shù)值清零
delay_ms(50);
return t;
}
float Getlenth()//通過(guò)聲音信號(hào)以及定時(shí)器定時(shí)的時(shí)間測(cè)得障礙物距離傳感器的距離
{
u32 t=0;
int i=0;
float lenthtemp=0;
float sum=0;
while(i!=10)
{
start();
while(Echo==0);
startim();
i=i+1;
while(Echo==1);
TIM_Cmd(TIM3, DISABLE);
t=GetEchoTimer();
lenthtemp=(float)t/58.0;//相當(dāng)于乘以0.017
sum=sum+lenthtemp;
}
lenthtemp=sum/10;
return lenthtemp;
}
/**********/
/**主函數(shù)**/
int main(void)
{
float lenth;
delay_init();
uart_init(115200);
LCD_Init();
TIMER3_Init(1000-1,72-1);
Init_SR();
while(1)
{
lenth=Getlenth();
printf("測(cè)得距離為: %f \r\n",lenth);
delay_ms(1000);
}
}
|
評(píng)分
-
查看全部評(píng)分
|