STM32超声波计数代码
时间: 2023-12-20 13:26:00 浏览: 135
以下是一个基于STM32的超声波计数代码示例,使用的是STM32F103C8T6开发板和HC-SR04超声波传感器。
```c
#include "stm32f10x.h"
#include "stdio.h"
#define TRIG_PIN GPIO_Pin_0
#define ECHO_PIN GPIO_Pin_1
void delay_us(uint32_t us)
{
uint32_t count = us * 8;
while(count--);
}
void TIM2_init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = SystemCoreClock / 1000000 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
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);
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM2, ENABLE);
}
void GPIO_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = TRIG_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void TIM2_IRQHandler(void)
{
static uint16_t overflow_cnt = 0;
static uint32_t last_capture_time = 0;
static uint32_t current_capture_time = 0;
static uint32_t pulse_width = 0;
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
overflow_cnt++;
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
if(GPIO_ReadInputDataBit(GPIOA, ECHO_PIN) == SET)
{
TIM_SetCounter(TIM2, 0);
overflow_cnt = 0;
}
if(GPIO_ReadInputDataBit(GPIOA, ECHO_PIN) == RESET && overflow_cnt > 0)
{
current_capture_time = TIM_GetCounter(TIM2) + overflow_cnt * 0xFFFF;
pulse_width = current_capture_time - last_capture_time;
last_capture_time = current_capture_time;
overflow_cnt = 0;
}
}
int main(void)
{
uint32_t distance = 0;
char buf[10];
GPIO_init();
TIM2_init();
while(1)
{
GPIO_SetBits(GPIOA, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(GPIOA, TRIG_PIN);
delay_us(60000);
distance = pulse_width / 58;
sprintf(buf, "%d cm\n", distance);
USART_SendString(USART1, buf);
}
}
```
代码中使用TIM2用作计时器,GPIOA的0号引脚用作超声波发射端口,GPIOA的1号引脚用作超声波接收端口。当超声波发射端口发出超声波时,计时器开始计时,当超声波接收端口接收到超声波时,计时器停止计时,计算超声波从发射到接收的时间差,进而计算出距离。最后将距离发送到串口调试助手中显示出来。
阅读全文