新手上路
- 积分
- 39
- 金钱
- 39
- 注册时间
- 2019-11-22
- 在线时间
- 10 小时
|
超声波模块测试遇到的问题,话不多说,我先上传我的代码:
我是用定时器计算超声波高电平持续时间,但在测试的时候总会出现错误的结果,这个结果还是一个固定的数字,还有负数.我不知道怎么回事,希望大家能帮我找出问题。谢谢@正点原子
【附上我的核心代码】
#include "SR04.h"
#include "SysTick.h"
u8 upcount;
u8 hightime;
void TIM6_IRQHandler ()
{
if (TIM_GetITStatus(TIM6, TIM_IT_Update))
{
TIM_ClearITPendingBit(TIM6, TIM_IT_Update);
upcount++;
}
}
void SR04_GPIOConfig()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE );
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_ResetBits(GPIOA, GPIO_Pin_2);
GPIO_ResetBits(GPIOA, GPIO_Pin_0);
}
void SR04_TIMConfig(u16 period,u16 pre)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE);
TIM_TimeBaseInitStructure.TIM_Period=period;
TIM_TimeBaseInitStructure.TIM_Prescaler=pre;
TIM_TimeBaseInit(TIM6, &TIM_TimeBaseInitStructure);
TIM_ITConfig( TIM6, TIM_IT_Update, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel=TIM6_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=0;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_Init( &NVIC_InitStructure);
TIM_ClearFlag(TIM6, TIM_FLAG_Update);
}
void SR04_Init()
{
SR04_TIMConfig(999,71);
SR04_GPIOConfig();
}
void SR04_Start()
{
GPIO_SetBits(GPIOA, GPIO_Pin_2);
delay_us(20);
GPIO_ResetBits(GPIOA, GPIO_Pin_2);
}
void OpenTimeForSR04()
{
TIM_Cmd(TIM6, ENABLE);
TIM_SetCounter(TIM6,0);//清空定时器
upcount=0;
}
void CloseTimeForSR04()
{
TIM_Cmd(TIM6, DISABLE);
// TIM_GetCounter(TIM6);
}
u32 GetHighTime()
{
u32 hightime;
hightime=upcount*1000;
hightime+=TIM_GetCounter(TIM6);
return hightime;
}
float SR04GetLengh()
{
u8 i=5;
u32 t=0;
float sumt,avglen;
while (i--) //循环计算五次
{
SR04_Start();
while ( GPIO_ReadInputDataBit( GPIOA, GPIO_Pin_0)==0);
OpenTimeForSR04();
while ( GPIO_ReadInputDataBit( GPIOA, GPIO_Pin_0)==1);
CloseTimeForSR04();
t=GetHighTime();
sumt+=t;
// delay_ms(60);
}
avglen=sumt/5/58.8;
return avglen;
}
函数主部分:
int main()
{
float len;
SysTick_Init(72);
LED_Init();
SR04_Init();
USART1_Init(9600);
while(1)
{
len=SR04GetLengh();
printf("这是一个超声波测试实验\r\n");
printf("测量的距离为:%0.3fcm\r\n",len);
delay_ms(1000);
}
}
|
|