最近在整超声波测距,与51相比还是不简单的,51有大量现成的程序可以直接套用,32很少的。只要把定时器配置好,引脚连接好,它用串口显示,还是oled显示都是不难的。
在这里超声波就不详细介绍了,记住他的引脚一个是trig(控制端),echo(接收端)配置这两个引脚是注意一下就好了。知道他们两个引脚对应的原理是什么。
我直接给大家分享一下这个项目中的程序
hcsr04.c
static void hcsr04_NVIC(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void hcsr04_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_ResetBits(GPIOB,GPIO_Pin_4);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB,&GPIO_InitStructure);
}
void TIM2_Init(u16 arr,u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_Time2_init;
TIM_Time2_init.TIM_Period = arr ;
TIM_Time2_init.TIM_Prescaler = psc;
TIM_Time2_init.TIM_ClockDivision =0 ;
TIM_Time2_init.TIM_CounterMode = TIM_CounterMode_Up;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInit(TIM2, &TIM_Time2_init);
}
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
usHcCount++;
}
}
static void OpenTimerForHc()
{
TIM_Cmd(TIM2, DISABLE);
TIM_SetCounter(TIM4,0);
usHcCount = 0;
TIM_Cmd(TIM2, ENABLE);
}
static void CloseTimerForHc()
{
TIM_Cmd(TIM2, DISABLE);
}
float GetEchoTimer(void)
{
float t = 0;
t = usHcCount;
t += TIM_GetCounter(TIM2)/100;
TIM2->CNT = 0;
return t;
}
int get_dis(void)
{
int i;
float sum=0;
for(i=0;i<5;i++)
{
GPIO_SetBits(GPIOB,GPIO_Pin_4);
delay_us(15);
GPIO_ResetBits(GPIOB,GPIO_Pin_4);
while(!GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_3));
TIM_Cmd(TIM2,ENABLE);
while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_3));
TIM_Cmd(TIM2,DISABLE);
sum+=(TIM_GetCounter(TIM2)*1.7)/100.0;
TIM_SetCounter(TIM2,0);
delay_ms(10);
}
sum/=5;
return sum;
}
如果是串口显示的话,可以参考下面的 main.c
int main()
{
float distance;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
hcsr04_Init();
uart_init(115200);
delay_init();
while(1)
{
printf("距离为:%f\n",get_dis());
delay_ms(2000);
}
}
大家可以参考一下,日后我还会日常更新的。
|