写一个STM32使用TIM3通道1的HC-SR04测距函数
时间: 2023-05-12 07:03:27 浏览: 110
STM32G030J6M6_HC-SR04.rar
5星 · 资源好评率100%
好的,以下是使用STM32使用TIM3通道1的HC-SR04测距函数的代码:
```
#include "stm32f10x.h"
#define TRIG_PIN GPIO_Pin_0
#define TRIG_PORT GPIOA
#define ECHO_PIN GPIO_Pin_6
#define ECHO_PORT GPIOB
void delay_us(uint32_t us)
{
uint32_t ticks;
ticks = us * (SystemCoreClock / 1000000);
while(ticks--);
}
float hc_sr04_measure_distance(void)
{
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
delay_us(2);
GPIO_SetBits(TRIG_PORT, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
while(!GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN));
uint32_t start = SysTick->VAL;
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN));
uint32_t end = SysTick->VAL;
float distance = (start - end) * 0.034 / 2;
return distance;
}
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
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);
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(ECHO_PORT, &GPIO_InitStructure);
while(1)
{
float distance = hc_sr04_measure_distance();
// do something with distance
}
}
```
希望这个函数对你有所帮助!
阅读全文