本帖最后由 arao和xiaomi 于 2017-4-5 08:59 编辑
就是有时候能测试准确,但是有时候会有两厘米的误差,感觉不是很稳定,不知道是什么原因,大神帮看一下呗
#include "ultrasonic.h"
#include "sys.h"
#include "delay.h"
#define TRIG_PORT GPIOB //TRIG
#define ECHO_PORT GPIOB //ECHO
#define TRIG_PIN GPIO_Pin_0 //TRIG
#define ECHO_PIN GPIO_Pin_10 //ECHO
float Ultrasonic_Distance; //计算出的距离
u8 check_data_state;
void Ultrasonic_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
//GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable , ENABLE); //关闭jtag
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO,ENABLE);
GPIO_InitStructure.GPIO_Pin=TRIG_PIN; //PB0接TRIG 备注5伏供电
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP; //设置为推挽输出模式
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(TRIG_PORT,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=ECHO_PIN; //PB10接ECHO
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPD; //设置为输入
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(ECHO_PORT,&GPIO_InitStructure);
//PE8 中断线以及中断初始化配置
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource10);
EXTI_InitStructure.EXTI_Line=EXTI_Line10;
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 = EXTI15_10_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
float EXTI15_10_IRQHandler(void)
{
delay_us(10);
if(EXTI_GetITStatus(EXTI_Line10) != RESET)
{
TIM_SetCounter(TIM2,0);
TIM_Cmd(TIM2, ENABLE);
while(GPIO_ReadInputDataBit(ECHO_PORT,ECHO_PIN));
TIM_Cmd(TIM2, DISABLE);
Ultrasonic_Distance=TIM_GetCounter(TIM2)*9.8*34/200.0;
if(Ultrasonic_Distance>0)
{
printf("distance:%f cm",Ultrasonic_Distance);
LCD_ShowString(30,150,200,16,16,"Ultrasonic TEST is OK");
}else
LCD_ShowString(30,150,200,16,16,"Ultrasonic TEST is error");
EXTI_ClearITPendingBit(EXTI_Line10);
}
check_data_state=1;
return Ultrasonic_Distance;
}
/*
* 初始化的时候,需要输出10us以上的TTL电平
*
*
*
*/
void Ultrasonic_StartMeasure(void)
{
GPIO_SetBits(TRIG_PORT,TRIG_PIN);
delay_us(20);
GPIO_ResetBits(TRIG_PORT,TRIG_PIN);
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
如果中断频率较高,而中断服务函数占用时间又比较长,有可能丢失部分中断,所以要求中断服务函数占用时间尽可能短
一周热门 更多>