2 超声波代码:
#include "stm32f10x.h"
#include "Delay.h"
#include "Timer.h"
#include "OLED.h"
//参数初始化
float Num;
int i=0,Counter,Sum,Dec,CNT_Mean,CN1,CN2;
//超声波模块触发函数
void SR04_Start(void)
{
GPIO_SetBits(GPIOA,GPIO_Pin_0);//A0置1大于10us
Delay_us(15);
GPIO_ResetBits(GPIOA,GPIO_Pin_0);
}
void SR04_Init(void)
{
Timer_Init();//开启定时器3
GPIO_InitTypeDef GPIO_InitStructure;//定义初始化结构体
EXTI_InitTypeDef EXTI_InitStructure;//定义外部中断结构体
NVIC_InitTypeDef NVIC_InitStructure;//定义NVIC结构体
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//开GPIO时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);//开AFIO时钟
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA,GPIO_PinSource1);
EXTI_InitStructure.EXTI_Line=EXTI_Line1;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
//脉冲触发端口 Trig=PA0
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 ;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//回波接收端口 Echo=PA1
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
SR04_Start();
}
void EXTI1_IRQHandler(void)
{
Delay_us(50);
if(EXTI_GetITStatus(EXTI_Line1) != RESET)
{
Timer_ON();//开始计时
CN1 = TIM_GetCounter(TIM2);
while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_1));//A1为高电平时一直循环下去
CN2 = TIM_GetCounter(TIM2);
Timer_OFF();
Counter = CN2 - CN1;//获得计数差
EXTI_ClearITPendingBit(EXTI_Line1);//清除标志位
}
}
void Show_SRDis(void)
{
for(i=0;i<5;i++)//均值滤波
{
SR04_Init();
Sum+=Counter;
}
CNT_Mean=Sum/5;
Num=CNT_Mean*0.017;//b/5 * 17/1000
Dec=(17*Sum/5)%100;//100取余得到小数点后值
OLED_ShowNum(1,7,Num,3);
OLED_ShowNum(1,11,Dec,2);
Delay_ms(100);
Sum=0;//更新Sum
}
//返回超声波测距值
float Get_DisVal(void)
{
return Num;
}
|