STM32怎么驱动超声波测距模块HC-SR04,并在OLED屏幕显示的代码的程序代码
时间: 2023-05-22 09:06:14 浏览: 270
以下是使用STM32驱动超声波测距模块HC-SR04,并在OLED屏幕显示的代码的程序代码:
```c
#include "stm32f10x.h"
#include "oled.h"
#define TRIG GPIO_Pin_8
#define ECHO GPIO_Pin_9
#define TIM TIM2
vu8 SYS_CLK=72;
vu16 Time=0;
vu16 Dis=0;
void TIM2_Init(u16 period,u16 prescaler)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
TIM_TimeBaseStructure.TIM_Period =period;
TIM_TimeBaseStructure.TIM_Prescaler = prescaler;
TIM_TimeBaseStructure.TIM_ClockDivision =TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode =TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM,&TIM_TimeBaseStructure);
TIM_ITConfig(TIM,TIM_IT_Update,ENABLE);
NVIC_InitStructure.NVIC_IRQChannel=TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=0;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM,TIM_IT_Update))
{
if(Time>0) Time--;
TIM_ClearITPendingBit(TIM,TIM_FLAG_Update);
}
}
void init_HC_SR04(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE,ENABLE);
GPIO_InitStructure.GPIO_Pin=TRIG;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOE,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=ECHO;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOE,&GPIO_InitStructure);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
TIM_Cmd(TIM,ENABLE);
}
void Trig_HC_SR04(void)
{
GPIO_SetBits(GPIOE,TRIG);
delay_us(15);
GPIO_ResetBits(GPIOE,TRIG);
}
u16 GetEchoTime_HC_SR04(void)
{
u16 echo_time=0;
while(GPIO_ReadInputDataBit(GPIOE,ECHO)==RESET);
while(GPIO_ReadInputDataBit(GPIOE,ECHO)==SET)
{
Time=65000;
echo_time++;
delay_us(10);
if(Time==0)break;
}
return echo_time;
}
u16 GetDis_HC_SR04(void)
{
u16 dis_num=0;
Trig_HC_SR04();
dis_num=GetEchoTime_HC_SR04();
return(dis_num * 0.017);
}
int main(void)
{
SystemInit();
if(SysTick_Config(SystemCoreClock/1000))while(1);
init_HC_SR04();
OLED_Init();
OLED_Clear();
OLED_ShowString(0,0,"Super-Sonic");
OLED_ShowString(0,2,"Distance test:");
OLED_ShowString(0,4,"----------------");
OLED_ShowString(0,6,"Author:EMANOK");
while(1)
{
Delay(50);
Dis=GetDis_HC_SR04();
OLED_ShowNum(0, 5, Dis, 3, 16);
OLED_ShowString(36, 5, "cm ");
}
}
```
希望这些代码能对你有所帮助!
阅读全文