|
为什么会无法测距?是程序上的错误,还是我没有写完全?
但是网上的程序与这个差别不大
#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "HCSR04.h"
int main(void)
{
delay_init(); //延时函数初始化
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级
uart_init(115200); //串口初始化为115200
HCSR04_Init();
while(1)
{
float T=gettime();
int i;
float s=0;
float t=0;
float a=0;
while(i=0,i<5,i++)
{
t=T*170/1000;
s=t+s;
}
a=s/5;
printf("距离为:%d cm\r\n",a);//打印总的距离
delay_ms(1000);
}
}
以上是主函数
#include "HCSR04.h"
#include "delay.h"
int n=0;
int time=0;
void HCSR04_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //使能PB端口时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13; //PB.13 端口配置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口速度为50MHz
GPIO_Init(GPIOB, &GPIO_InitStructure); //根据设定参数初始化GPIOB.13
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14; //PB.14 端口配置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; //下拉输入
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口速度为50MHz
GPIO_Init(GPIOB, &GPIO_InitStructure); //根据设定参数初始化GPIOB.14
//定时器TIM3初始化
TIM_TimeBaseStructure.TIM_Period =10000-1; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值
TIM_TimeBaseStructure.TIM_Prescaler =7200-1; //设置用来作为TIMx时钟频率除数的预分频值
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); //根据指定的参数初始化TIMx的时间基数单位
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); //使能指定的TIM3中断,允许更新中断
//中断优先级NVIC设置
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //TIM3中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //先占优先级0级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //从优先级3级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道被使能
NVIC_Init(&NVIC_InitStructure); //初始化NVIC寄存器
TIM_Cmd(TIM3,ENABLE);
}
void TIM3_IRQHandler(void) //TIM3中断
{
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) //检查TIM3更新中断发生与否
{
n+=1;
}
TIM_ClearITPendingBit(TIM3, TIM_IT_Update ); //清除TIMx更新中断标志
}
float gettime(void)//时间获取函数
{
GPIO_ResetBits(GPIOB,GPIO_Pin_13); //预拉低trig引脚
delay_ms(20);
GPIO_SetBits(GPIOB,GPIO_Pin_13);
delay_ms(20);
GPIO_ResetBits(GPIOB,GPIO_Pin_13);//发出脉冲
if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_14)==0)//等待信号发出,信号发出,计数器置0,同时变为高电平
{
TIM3->CNT=0;//清零
}
if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_14)==1)//等待信号接收,信号发出时,引脚一直置1
{
time=TIM3->CNT;//获取时间
return time;
}
}
//以上是超声波模块的
|
|