1.首先配置使能的GPIO端口 (这里通过配置GPIOE端口)
1.1、第0位引脚作为触发端(发射)
void GPIOE0_Init()
{
RCC->AHB1ENR |= 1<<4;
GPIOE->MODER &= ~(3<<0);
GPIOE->MODER |= (1<<0);
GPIOE->OTYPER &= ~(1<<0);
GPIOE->OSPEEDR |= (3<<0);
GPIOE->PUPDR &= ~(3<<0);
GPIOE->PUPDR |= (2<<0);
}
1.2、第1位引脚作为回收端(接收)
void GPIOE1_Init_IN()
{
RCC->AHB1ENR |= 1<<4;
GPIOE->MODER &= ~(3<<2);
GPIOE->PUPDR &= ~(3<<2);
GPIOE->PUPDR |= (2<<2);
}
2.配置PE1输入数据端-作检测
int Check_E1()
{
int r = GPIOE->IDR & (1<<1);
if(r!=0)
return 1;
else
return 0;
}
3.us定时器中断
u32 US_Tick;
void Timer4_Init()
{
RCC->APB1ENR |= 1<<2;
TIM4->PSC=42-1;
TIM4->ARR=2-1;
TIM4->DIER |= 1<<0;
TIM4->CR1 |= 1<<0;
MY_NVIC_InitG2(0,1,TIM4_IRQn);
}
void TIM4_IRQHandler(void)
{
int r = TIM4->SR & 0x0001;
if(r!=0)
{
TIM4->SR &= ~(1<<0);
US_Tick++;
}
}
void My_Delay_US( u32 s )
{
u32 tmp = US_Tick;
while(1)
{
if( US_Tick - tmp >= s )
{
return;
}
}
}
4.超声波工作函数
void SR04_Work()
{
double t1,t2;
double distance;
SW_E0(1);
My_Delay_US(30);
SW_E0(0);
while(1)
{
if(Check_E1()==1)
{
t1=US_Tick;
break;
}
}
while(1)
{
if(Check_E1()==0)
{
t2=US_Tick;
break;
}
}
distance=(t2-t1)/1000000.0f*340.0f/2.0f*100.0f;
printf("%.2lfcm\n",distance);
}
时序图如下:
每两秒检测一次,通过串口通信打印结果
效果如下:
|