stm32超聲波測距程序
單片機(jī)用的是STM32F103VC系列,超聲波是淘寶買的一個(gè)模塊,只有5個(gè)引腳,用起來很方便。
用的時(shí)候只需要其中4個(gè)腳,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();//定時(shí)器初始化函數(shù)
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,發(fā)射超聲波
GPIO_ResetBits(GPIOA,GPIO_Pin_8);
TIM2->CNT=0;//計(jì)數(shù)器清0
while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_9)==0);//等待ECHO腳高電平
TIM_Cmd(TIM2, ENABLE);// TIM2 enable counter [允許tim2計(jì)數(shù)]
while((GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_9)==1)&&(TIM2->CNTARR-10));
TIM_Cmd(TIM2, DISABLE);
count=TIM2->CNT;//ECHO腳低電平后讀取計(jì)數(shù)器的值,從而算出往返時(shí)間
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);//復(fù)位TIM2定時(shí)器
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);
}
評(píng)論