基于MM32写出一个利用HC-SR04实现超声波测距功能,并显示在串口中
时间: 2024-03-25 11:36:29 浏览: 188
两路超声波测距,超声波测速,HC-SR04传感器,显示距离和速度在LCD屏幕和串口,32F103核心板,直线上碰撞检测。
5星 · 资源好评率100%
好的,下面是一个基于MM32的代码示例,实现了利用HC-SR04超声波模块测距,并将测得的距离通过串口输出显示。
```c
#include "MM32F103.h"
#include "stdio.h"
#define TRIG_PIN GPIO_Pin_0
#define ECHO_PIN GPIO_Pin_1
void GPIO_Configuration(void);
void TIM_Configuration(void);
void USART_Configuration(void);
void delay_us(uint32_t us);
void delay_ms(uint32_t ms);
void USART_SendString(USART_TypeDef* USARTx, char* str);
int main(void)
{
uint32_t distance = 0;
char str[32] = {0};
GPIO_Configuration();
TIM_Configuration();
USART_Configuration();
while(1)
{
GPIO_ResetBits(GPIOA, TRIG_PIN);
delay_us(2);
GPIO_SetBits(GPIOA, TRIG_PIN);
delay_us(10);
GPIO_ResetBits(GPIOA, TRIG_PIN);
while(GPIO_ReadInputDataBit(GPIOA, ECHO_PIN) == RESET);
TIM_SetCounter(TIM2, 0);
while(GPIO_ReadInputDataBit(GPIOA, ECHO_PIN) == SET);
distance = TIM_GetCounter(TIM2) * 0.034 / 2;
sprintf(str, "Distance: %d cm\n", distance);
USART_SendString(USART1, str);
delay_ms(500);
}
}
void GPIO_Configuration(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(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = ECHO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_ResetBits(GPIOA, TRIG_PIN);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
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);
}
void USART_Configuration(void)
{
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void delay_us(uint32_t us)
{
uint32_t i, j;
for(i = 0; i < us; i++)
{
for(j = 0; j < 8; j++);
}
}
void delay_ms(uint32_t ms)
{
uint32_t i, j;
for(i = 0; i < ms; i++)
{
for(j = 0; j < 8000; j++);
}
}
void USART_SendString(USART_TypeDef* USARTx, char* str)
{
while(*str)
{
USART_SendData(USARTx, (uint16_t)(*str++));
while(USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET);
}
}
```
需要注意的是,本代码示例中使用的是PA0和PA1引脚分别连接TRIG和ECHO引脚,需要根据实际硬件连接情况进行修改。同时,在使用测距功能时,需要将超声波模块与待测物体之间保持一定距离,避免测量出的距离受到干扰。
阅读全文