標(biāo)題: 手寫一個(gè)簡(jiǎn)單的STM32超聲波測(cè)距程序 [打印本頁(yè)]

作者: a1418414974    時(shí)間: 2019-7-27 21:21
標(biāo)題: 手寫一個(gè)簡(jiǎn)單的STM32超聲波測(cè)距程序
實(shí)現(xiàn)的功能:通過HC-SR04測(cè)得距離障礙物的距離,并通過串口打印


/**********/
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()//打開定時(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()//通過聲音信號(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);
        }
}


作者: a1418414974    時(shí)間: 2019-7-27 21:25
經(jīng)測(cè)試,該程序可行
作者: 伊特    時(shí)間: 2019-8-2 18:10
有沒有完整的程序
作者: 伊特    時(shí)間: 2019-8-2 18:11
a1418414974 發(fā)表于 2019-7-27 21:25
經(jīng)測(cè)試,該程序可行

有沒有完整的程序還有接線圖
作者: 1604572292    時(shí)間: 2019-8-6 16:27
a1418414974 發(fā)表于 2019-7-27 21:25
經(jīng)測(cè)試,該程序可行

有網(wǎng)整成序馬




歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1