生活随笔
收集整理的这篇文章主要介绍了
STM32基础——超声波测距+OLED显示+蜂鸣器报警
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
此代码的格式可以直接烧录到STMF03C8T6最小系统中,烧录在其它芯片需要自己进行代码移植,功能是使用超声波模块进行测距,距离会显示在OLED屏幕上,并且当测量到的数据小于设定的范围是,蜂鸣器报警,可以适用在智能小车的倒车提示功能上。因为三个模块的代码过多,只展示一部分,完整代码私聊拿。
超声波测距模块代码:
.c文件
#include "stm32f10x.h" #include "HCSR04.h"
#include "delay.h"int N
=0;
float distance
=0;
void My_CSB_Init(void)
{GPIO_InitTypeDef GPIO_InitStructure
;NVIC_InitTypeDef NVIC_InitStructure
;TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure
;RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB
, ENABLE
); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2
, ENABLE
);GPIO_InitStructure
.GPIO_Pin
= GPIO_Pin_10
;GPIO_InitStructure
.GPIO_Mode
= GPIO_Mode_Out_PP
; GPIO_InitStructure
.GPIO_Speed
= GPIO_Speed_50MHz
; GPIO_Init(GPIOB
, &GPIO_InitStructure
); GPIO_InitStructure
.GPIO_Pin
= GPIO_Pin_11
;GPIO_InitStructure
.GPIO_Mode
= GPIO_Mode_IPU
; GPIO_InitStructure
.GPIO_Speed
= GPIO_Speed_50MHz
; GPIO_Init(GPIOB
, &GPIO_InitStructure
);TIM_TimeBaseStructure
.TIM_Period
= 49999;TIM_TimeBaseStructure
.TIM_Prescaler
= 72-1;TIM_TimeBaseStructure
.TIM_ClockDivision
= TIM_CKD_DIV1
; TIM_TimeBaseStructure
.TIM_CounterMode
= TIM_CounterMode_Up
;TIM_TimeBaseInit(TIM2
, &TIM_TimeBaseStructure
); TIM_ITConfig(TIM2
,TIM_IT_Update
,ENABLE
);NVIC_InitStructure
.NVIC_IRQChannel
= TIM2_IRQn
; NVIC_InitStructure
.NVIC_IRQChannelPreemptionPriority
= 1; NVIC_InitStructure
.NVIC_IRQChannelSubPriority
= 0; NVIC_InitStructure
.NVIC_IRQChannelCmd
= ENABLE
; NVIC_Init(&NVIC_InitStructure
); TIM_Cmd(TIM2
, ENABLE
);
}
void TIM2_IRQHandler(void)
{if(TIM_GetITStatus(TIM2
, TIM_IT_Update
) != RESET
){N
+= 1; }TIM_ClearITPendingBit(TIM2
, TIM_IT_Update
);
}int count
=0;
float Distance(void)
{GPIO_ResetBits(GPIOB
, GPIO_Pin_10
);GPIO_SetBits(GPIOB
, GPIO_Pin_10
);delay_us(20);GPIO_ResetBits(GPIOB
, GPIO_Pin_10
);while(GPIO_ReadInputDataBit(GPIOB
, GPIO_Pin_11
) == 0);
TIM2
->CNT
=0;while(GPIO_ReadInputDataBit(GPIOB
, GPIO_Pin_11
) == 1); count
=TIM2
->CNT
;
distance
=(float)count
/58.5; return distance
;
}
.h文件
#ifndef __HCSR04_H
#define __HCSR04_H
#include "sys.h"void My_CSB_Init(void);
float Distance(void);#endif
总结
以上是生活随笔为你收集整理的STM32基础——超声波测距+OLED显示+蜂鸣器报警的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。