stm32超声波测距并在OLED上显示距离
时间: 2023-10-19 16:17:24 浏览: 149
以下是基于STM32的超声波测距并在OLED上显示距离的代码:
```c
#include "stm32f10x.h"
#include "delay.h"
#include "oled.h"
#define TRIG_PIN GPIO_Pin_0
#define TRIG_PORT GPIOA
#define ECHO_PIN GPIO_Pin_1
#define ECHO_PORT GPIOA
void TIM2_Init(void);
void GPIO_Init(void);
void Display_Distance(float distance);
int main(void)
{
TIM2_Init(); // 初始化定时器2
GPIO_Init(); // 初始化GPIO
Delay_Init(); // 初始化延时函数
OLED_Init(); // 初始化OLED
while(1)
{
TIM_SetCounter(TIM2, 0); // 计数器清零
GPIO_SetBits(TRIG_PORT, TRIG_PIN); // 发送一个高电平脉冲
Delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN); // 将脉冲拉低
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET); // 等待回波信号
TIM_Cmd(TIM2, ENABLE); // 启动定时器2
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == SET); // 等待回波信号结束
TIM_Cmd(TIM2, DISABLE); // 关闭定时器2
float distance = TIM_GetCounter(TIM2) / 58.0; // 计算距离
Display_Distance(distance); // 在OLED上显示距离
Delay_ms(1000);
}
}
void TIM2_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
NVIC_InitTypeDef NVIC_InitStruct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); // 使能定时器2时钟
TIM_TimeBaseInitStruct.TIM_Period = 0xffff;
TIM_TimeBaseInitStruct.TIM_Prescaler = SystemCoreClock / 1000000 - 1;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
NVIC_InitStruct.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
}
void GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); // 使能GPIOA时钟
GPIO_InitStruct.GPIO_Pin = TRIG_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(TRIG_PORT, &GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = ECHO_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(ECHO_PORT, &GPIO_InitStruct);
}
void Display_Distance(float distance)
{
char str[20];
sprintf(str, "Distance: %.2f cm", distance);
OLED_Clear();
OLED_ShowString(0, 0, (uint8_t*)str);
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
```
在代码中,我们添加了OLED初始化函数和显示距离的函数。在显示距离的函数中,我们使用sprintf函数将距离转换为字符串,然后将其显示在OLED上。在主函数中,我们调用显示距离的函数来实时显示距离。
阅读全文