stm32超声波测距程序
单片机用的是
STM32F103VC系列,超声波是淘宝买的一个模块,只有5个引脚,用起来很方便。
用的时候只需要其中4个脚,VCC,GND,TRIG,ECHO。 TRIG接PA8,OUT_PP模式;ECHO接PA9,IN_FLOATING模式。
#include "
stm32f10x_heads.h"
#include "HelloRobot.h"
#include "display.h"
void Tim2_Init(void);
void TIM2_IRQHandler(void)
{
if(GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_12)==0)
GPIO_SetBits(GPIOE,GPIO_Pin_12);
else
GPIO_ResetBits(GPIOE,GPIO_Pin_12);
TIM_ClearFlag(TIM2, TIM_FLAG_Update);
}
int main(void)
{
u16 count;
float length;
BSP_Init();
Tim2_Init();//定时器初始化函数
LCM_Init();
delay_nms(5);
GPIO_ResetBits(GPIOA,GPIO_Pin_8);
Display_List_Char(1,0,"distance:"); //PA8:Trig PA0:Echo
while (1)
{
GPIO_SetBits(GPIOA,GPIO_Pin_8);
delay_nus(20);//拉高超过10us,发射超声波
GPIO_ResetBits(GPIOA,GPIO_Pin_8);
TIM2->CNT=0;//计数器清0
while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_9)==0);//等待ECHO脚高电平
TIM_Cmd(TIM2, ENABLE);// TIM2 enable counter [允许tim2计数]
while((GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_9)==1)&&(TIM2->CNT
ARR-10));
TIM_Cmd(TIM2, DISABLE);
count=TIM2->CNT;//ECHO脚低电平后读取计数器的值,从而算出往返时间
length=count/58.0;
Display_List_Char(1,9," ");
Display_List_Float(1,9,length);
delay_nms(200);
}
}
void Tim2_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_DeInit(TIM2);//复位TIM2定时器
TIM_TimeBaseStructure.TIM_Period = 49999;
TIM_TimeBaseStructure.TIM_Prescaler = 71;
TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, & TIM_TimeBaseStructure);
TIM_ClearFlag(TIM2, TIM_FLAG_Update);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
}
评论