标题: 手写一个简单的STM32超声波测距程序 [打印本页]

作者: a1418414974    时间: 2019-7-27 21:21
标题: 手写一个简单的STM32超声波测距程序
实现的功能:通过HC-SR04测得距离障碍物的距离,并通过串口打印


/**********/
u16 cnt=0;

void Init_SR()//初始化PB5,PB6 PB5控制Trig,PB6感应Echo的接收信号
{
        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()//输出一个十微秒的方波,使传感器发出超声波,起始信号
{
        Trig=1;
        delay_us(20);
        Trig=0;
}
void startim()//打开定时器
{
        TIM_SetCounter(TIM3,0);
        cnt=0;
        TIM_Cmd(TIM3, ENABLE);
}
void TIM3_IRQHandler(void)//定时器中断
{
        if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET)
        {
                cnt++;//cnt每加一次,代表定时一微秒
                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计数寄存器的计数值清零
                delay_ms(50);
                return t;
}
float Getlenth()//通过声音信号以及定时器定时的时间测得障碍物距离传感器的距离
{
        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;//相当于乘以0.017
                sum=sum+lenthtemp;
        }
        lenthtemp=sum/10;
        return lenthtemp;
}

/**********/



/**主函数**/

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("测得距离为: %f \r\n",lenth);
                 delay_ms(1000);
        }
}


作者: a1418414974    时间: 2019-7-27 21:25
经测试,该程序可行
作者: 伊特    时间: 2019-8-2 18:10
有没有完整的程序
作者: 伊特    时间: 2019-8-2 18:11
a1418414974 发表于 2019-7-27 21:25
经测试,该程序可行

有没有完整的程序还有接线图
作者: 1604572292    时间: 2019-8-6 16:27
a1418414974 发表于 2019-7-27 21:25
经测试,该程序可行

有网整成序马




欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1