超声波测距,定时器中断计时

2019-08-17 09:16发布

我用HY-SRF05超声波传感器测距,时间用定时器溢出计数,中断!
不是很懂,求大神讲解整个过程是怎样的,我原本是这样简单理解的,TRIG端发送一个高电平,设置为20us,其发送8个40KHZ的方波,一发送完ECHO脚就拉高,并检测是否有信号。如果有高电平信号存在就开启STM32的定时器TIM4接收高电平并计时,一旦检测不到高电平就关闭计时器,检测时间即为我们需要的。
#include "ultrasonic.h"
#include "delay.h"
#include "stm32f10x.h"


extern short tm;
int overcount1=0;

void NVIC_Config(void)
{
NVIC_InitTypeDef NVIC_InitStructer;
NVIC_InitStructer.NVIC_IRQChannelPreemptionPriority=0;
NVIC_InitStructer.NVIC_IRQChannelSubPriority=3;
NVIC_InitStructer.NVIC_IRQChannel=TIM4_IRQn;
NVIC_InitStructer.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructer);
}

void Ultrasonic_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructer;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructer;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
       

GPIO_InitStructer.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructer.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStructer.GPIO_Pin=GPIO_Pin_5;
GPIO_Init(GPIOB, &GPIO_InitStructer);


GPIO_InitStructer.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_InitStructer.GPIO_Pin=GPIO_Pin_4;
GPIO_Init(GPIOB, & GPIO_InitStructer);


TIM_DeInit(TIM4);
TIM_TimeBaseInitStructer.TIM_Period=999;
TIM_TimeBaseInitStructer.TIM_Prescaler=71;
TIM_TimeBaseInitStructer.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInitStructer.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM4,&TIM_TimeBaseInitStructer);
TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE);


NVIC_Config();
TIM_Cmd(TIM4,DISABLE);


}


float Distance_Gets(void)
{

float length=0,sum=0;
u16 tim;
int i=0;

while(i!=5)
{
  GPIO_SetBits(GPIOB,GPIO_Pin_5);
  delay_us(20);  
  GPIO_ResetBits(GPIOB,GPIO_Pin_5);

  while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_4)==RESET);
  TIM_Cmd(TIM4,ENABLE);
  while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_4)==SET);

  TIM_Cmd(TIM4,DISABLE);

  tim=TIM_GetCounter(TIM4);

  length=(tim*(331.4+0.607*(tm/10+0.46))/20+overcount1*(331.4+0.607*(tm/10+0.46))*50)/1000;

  i++; //′Îêy
  sum=length+sum;
  TIM4->CNT=0;  
  overcount1=0;  
  delay_ms(100);







}
length=sum/5;
return length;

}



void TIM4_IRQHandler(void)
{
if(TIM_GetITStatus(TIM4,TIM_IT_Update)!=RESET)

  {
TIM_ClearITPendingBit(TIM4,TIM_IT_Update);

overcount1++;

  }
}


0条回答

一周热门 更多>