STM32F103C8T6的基础上使用keil5编程,请编写一份HC-SR04超声波传感器的.c和.h文件,要求实现测距功能,将测量值转化为毫米单位
时间: 2024-02-28 18:54:10 浏览: 82
以下是基于STM32F103C8T6和Keil5的HC-SR04超声波传感器的.c和.h文件,实现测距功能,并将测量值转化为毫米单位。
.h文件:
```c
#ifndef __ULTRASONIC_H
#define __ULTRASONIC_H
#include "stm32f10x.h"
#define TRIG_PIN GPIO_Pin_0
#define TRIG_PORT GPIOA
#define ECHO_PIN GPIO_Pin_1
#define ECHO_PORT GPIOA
void Ultrasonic_Init(void);
uint32_t Ultrasonic_GetDistance(void);
#endif /* __ULTRASONIC_H */
```
.c文件:
```c
#include "ultrasonic.h"
void Ultrasonic_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(TRIG_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(ECHO_PORT, &GPIO_InitStructure);
}
uint32_t Ultrasonic_GetDistance(void)
{
uint32_t distance;
uint32_t timeout;
uint32_t start_time, end_time;
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
delay_us(2);
GPIO_SetBits(TRIG_PORT, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(TRIG_PORT, TRIG_PIN);
timeout = 40000;
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == RESET)
{
if(timeout-- == 0)
{
return 0;
}
}
start_time = TIM2->CNT;
timeout = 40000;
while(GPIO_ReadInputDataBit(ECHO_PORT, ECHO_PIN) == SET)
{
if(timeout-- == 0)
{
return 0;
}
}
end_time = TIM2->CNT;
distance = ((end_time - start_time) * 1000) / 58; // 转化为毫米单位
return distance;
}
```
需要注意的是,此处使用了定时器TIM2来计算回声信号的持续时间。在main函数中需要先对TIM2进行初始化,具体可以参考以下代码:
```c
#include "stm32f10x.h"
#include "ultrasonic.h"
void TIM2_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Prescaler = (SystemCoreClock / 1000000) - 1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = 0xFFFFFFFF;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_Cmd(TIM2, ENABLE);
}
int main(void)
{
uint32_t distance;
TIM2_Init();
Ultrasonic_Init();
while(1)
{
distance = Ultrasonic_GetDistance();
// 处理测量值
}
}
```
其中,SystemCoreClock是系统时钟频率,需要根据实际情况进行设置。此处假设系统时钟频率为72MHz。
阅读全文