这个是超声波模块的时序图,自己看看就可以了,代码备注了解释
Ultrasound.c部分代码
#include "stm32f10x.h" // Device header
#include "Delay.h"
void Timer_Init()
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef GPIO_InitTypeStruct;
GPIO_InitTypeStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;//采用浮空输入模式
GPIO_InitTypeStruct.GPIO_Pin = GPIO_Pin_0;//ECHO
GPIO_InitTypeStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitTypeStruct);
GPIO_InitTypeStruct.GPIO_Mode = GPIO_Mode_Out_PP;//推挽输出模式
GPIO_InitTypeStruct.GPIO_Pin = GPIO_Pin_1;//trig
GPIO_InitTypeStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitTypeStruct);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
TIM_InternalClockConfig(TIM2);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructuer;
TIM_TimeBaseInitStructuer.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructuer.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructuer.TIM_Period = 5000-1;
TIM_TimeBaseInitStructuer.TIM_Prescaler = 72-1;
TIM_TimeBaseInitStructuer.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructuer);
// TIM_ClearFlag(TIM2,TIM_FLAG_Update);//
// TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);//
TIM_Cmd(TIM2,DISABLE);
}
int Get_Count()
{
uint16_t Count=0;
GPIO_ResetBits(GPIOA,GPIO_Pin_1);//先拉低TRIG的引脚
GPIO_SetBits(GPIOA,GPIO_Pin_1);//走时序
Delay_us(15);
GPIO_ResetBits(GPIOA,GPIO_Pin_1);//再次拉低时序
TIM_SetCounter(TIM2,0);//清零计数器的值
while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) == 0);//先判断ECHO是否被拉低
TIM_Cmd(TIM2,ENABLE);;//拉低开始计数 开启计数器
while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) == 1);//拉高则结束计数
TIM_Cmd(TIM2,ENABLE);//计数结束关闭计数器
Count = TIM_GetCounter(TIM2);//取出计数器的值
Count = (int)Count/58;//单位CM
return Count-39;//减去39测出来的数值才对
}
Ultrasound.h部分代码
#ifndef __ULTRASOUND_H
#define __ULTRASOUND_H
void Timer_Init();
uint16_t Get_Count();
#endif
Main函数的调用
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "Ultrasound.h" // Device header
uint8_t KeyNum;
int main(void)
{
OLED_Init();
OLED_ShowChar(1,1,'A');
Timer_Init();
while(1)
{
Delay_us(1000);
OLED_ShowNum(2,1,Get_Count(),8);
}
}
代码上面最后测出的距离减39才对,至于为什么还没有发现