HC_SR04这款超声波测距模块的使用说明在网上都能找到,使用方法也很简单。所以我这里就直接上代码了,希望能够对大家有所帮助。
main.c
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "HCSR04.h"
#define Echo GPIO_Pin_8
#define Trig GPIO_Pin_9
uint32_t Count,Distance;
int main(void)
{
HCSR_Init();
OLED_Init();
OLED_ShowChar(1,1,'A');
GPIO_ResetBits(GPIOA,Trig);
while(1)
{
GPIO_SetBits(GPIOA,Trig);
Delay_us(12);
GPIO_ResetBits(GPIOA,Trig);
while(!GPIO_ReadInputDataBit(GPIOA,Echo));
TIM_Cmd(TIM2,ENABLE); //开启时钟
while(GPIO_ReadInputDataBit(GPIOA,Echo));
TIM_Cmd(TIM2,DISABLE); //关闭时钟
Count=TIM2->CNT; //将定时器2的计数值赋给Count
TIM_SetCounter(TIM2,0); //清空定时器计数
// OLED_ShowNum(2,5,Count,5);
Distance=Count*17/100; //计算实际距离(此处声速取340m/s)
OLED_ShowNum(3,5,Distance,5);
OLED_ShowString(3,10,"mm"); //显示测距结果:mm
Delay_ms(1000);
}
}
HCSR04 .c
#include "stm32f10x.h" // Device header
void HCSR_Init(void)
{
//配置GPIO
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_8;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;
GPIO_Init(GPIOA,&GPIO_InitStructure);
//配置时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_Period=30000-1; //ARR
TIM_TimeBaseInitStructure.TIM_Prescaler=72-1; //PSC
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
}
HCSR04.h
#ifndef __HCSR04_
#define __HCSR04_
void HCSR_Init(void);
#endif
程序中用的OLED驱动是江科大写的,工程文件打包放在下面,有需要的可以自行下载使用
链接:https://pan.baidu.com/s/1A46kaC64pPYGjSCmniWpYg
提取码:cgst