stm32f103rct6用库函数控制超声波代码
时间: 2023-10-02 14:06:24 浏览: 99
舵机的PID控制(两个自由度).zip_PID控制_stm32f103rct6单片机_两自由度舵机_舵机_舵机PID
5星 · 资源好评率100%
以下是使用库函数控制超声波模块的代码,适用于STM32F103RCT6:
```c
#include "stm32f10x.h"
#include "delay.h"
#include "lcd.h"
#include "usart.h"
#define Trig GPIO_Pin_7
#define Echo GPIO_Pin_6
void GPIO_Configuration(void);
void TIM_Configuration(void);
void NVIC_Configuration(void);
int main(void)
{
float distance;
char buffer[16];
GPIO_Configuration();
TIM_Configuration();
NVIC_Configuration();
USART_Configuration();
LCD_Configuration();
while(1)
{
GPIO_SetBits(GPIOB, Trig);
delay_us(10);
GPIO_ResetBits(GPIOB, Trig);
while(GPIO_ReadInputDataBit(GPIOB, Echo) == RESET);
TIM_Cmd(TIM2, ENABLE);
while(GPIO_ReadInputDataBit(GPIOB, Echo) == SET);
TIM_Cmd(TIM2, DISABLE);
distance = (float)TIM_GetCounter(TIM2) / 58.0;
sprintf(buffer, "Distance:%.2fcm", distance);
USART_SendString(buffer);
LCD_Clear();
LCD_DisplayStringLine(Line1, buffer);
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = Trig;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = Echo;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_Prescaler = 71;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
}
void NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
```
代码中使用了STM32F10x标准库,并且需要提前配置好LCD和USART。其中Trig和Echo分别对应超声波模块的Trig和Echo引脚,TIM2用于计时,计算出超声波返回的时间,进而计算出距离。在主函数中,不断获取距离并通过USART发送出去,同时在LCD上显示。注意,本代码中距离单位为厘米。
阅读全文