分享

STM32 超声波测距模块HCSR

 昵称44327354 2017-08-08
/******************************************************************************* Driver for HC-SR04 测试平台:STM32F103ZET6最小系统 引脚连接:TRIG--PC0 ECHO--PC1*******************************************************************************/#include 'sonar_hcsr04.h'#include 'systime.h'#define SONAR_PORT GPIOC#define TRIG_PIN GPIO_Pin_0#define ECHO_PIN GPIO_Pin_1static volatile uint32_t measurement;void hcsr04Init(void){ GPIO_InitTypeDef GPIO_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC , ENABLE); GPIO_InitStructure.GPIO_Pin = TRIG_PIN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(SONAR_PORT, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = ECHO_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(SONAR_PORT, &GPIO_InitStructure); GPIO_ResetBits(SONAR_PORT, ECHO_PIN); GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource1); // 中断线以及中断初始化配置 EXTI_ClearITPendingBit(EXTI_Line1); EXTI_InitStructure.EXTI_Line = EXTI_Line1; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); /* Enable TIM5 clock */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE); /* TIME5 base configuration */ TIM_TimeBaseInitStructure.TIM_Period = 0xFFFF; // TIM_TimeBaseInitStructure.TIM_Prescaler = 72-1; // 设置预分频,F=72MHz/72=1MHz,T=1us TIM_TimeBaseInitStructure.TIM_ClockDivision = 0; // 设置时钟分频系数,不分频 TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数模式 TIM_TimeBaseInit(TIM5, &TIM_TimeBaseInitStructure); // 初始化TIME5 TIM_Cmd(TIM5, DISABLE); }/** * 发出测试信号 */void hcsr04StartRanging(void){ GPIO_SetBits(SONAR_PORT, TRIG_PIN); delay_us(20); // The width of trig signal must be greater than 10us GPIO_ResetBits(SONAR_PORT, TRIG_PIN);}/** * 根据公式计算距离 * @return distance units:cm */float hcsr04GetDistance(void){ // distance = measurement/2/1000*340 = measurement/59 (cm) measurement-units:us float distance = measurement / 58.8; // measurement-units:us return distance;}static void ECHO_EXTI_IRQHandler(void){ if (EXTI_GetITStatus(EXTI_Line1) != RESET) { if (GPIO_ReadInputDataBit(SONAR_PORT, ECHO_PIN) != 0) { // 等待高电平回波 TIM_Cmd(TIM5, ENABLE); } else { TIM_Cmd(TIM5, DISABLE); measurement = TIM_GetCounter(TIM5); TIM_SetCounter(TIM5, 0); } } EXTI_ClearITPendingBit(EXTI_Line1);}void EXTI1_IRQHandler(void){ ECHO_EXTI_IRQHandler();}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多