357 Wait and Pulse 04

好的,以下是一个基于STM32的HC-SR04测距函数的示例代码: ``` #include "stm32f10x.h" #define TRIG_PIN GPIO_Pin_0 #define ECHO_PIN GPIO_Pin_1 #define TRIG_PORT GPIOA #define ECHO_PORT GPIOA void delay_us(uint32_t us) { uint32_t i; for(i=0; i<us*8; i++); } float hc_sr04_measure_distance(void) { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_ICInitTypeDef TIM_ICInitStructure; NVIC_InitTypeDef NVIC_InitStructure; float distance; uint32_t pulse_width; uint32_t timeout; // Enable GPIOA and TIM2 clocks RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); // Configure TRIG pin as output GPIO_InitStructure.GPIO_Pin = TRIG_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(TRIG_PORT, &GPIO_InitStructure); // Configure ECHO pin as input GPIO_InitStructure.GPIO_Pin = ECHO_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; GPIO_Init(ECHO_PORT, &GPIO_InitStructure); // Configure TIM2 for input capture mode TIM_TimeBaseStructure.TIM_Period = 0xFFFF; TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); TIM_ICInitStructure.TIM_Channel = TIM_Channel_2; TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; TIM_ICInitStructure.TIM_ICFilter = 0; TIM_ICInit(TIM2, &TIM_ICInitStructure); // Enable TIM2 interrupt NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); // Generate 10us pulse on TRIG pin GPIO_SetBits(TRIG_PORT, TRIG_PIN); delay_us(10); GPIO_ResetBits(TRIG_PORT, TRIG_PIN); // Wait for ECHO pin to go high timeout = 0; while(!GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN)) { if(timeout++ > 10000) return -1; } // Start TIM2 TIM_Cmd(TIM2, ENABLE); // Wait for ECHO pin to go low timeout = 0; while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN)) { if(timeout++ > 10000) return -1; } // Stop TIM2 TIM_Cmd(TIM2, DISABLE); // Calculate pulse width pulse_width = TIM_GetCapture2(TIM2); // Calculate distance in cm distance = pulse_width * 0.034 / 2; return distance; } void TIM2_IRQHandler(void) { TIM_ClearITPendingBit(TIM2, TIM_IT_CC2); } ``` 这个函数使用STM32的定时器和输入捕获功能来测量HC-SR04超声波传感器返回的脉冲宽度,并计算出距离。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄健华Yeah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值