STM32F103
请问
STM32F103如何通过串口USART控制LED亮灭?
回帖(1)
2021-12-7 09:41:46
本人使用的是正点原子购买的开发板——精英版STM32F103ZET6 这款开发板的其中一个LED引脚PB5,看下图
#代码直接放在main.c中编译,加入所需库函数
#include
#include
#include
#include
#include
#include
#include
//LED开关
#define LED_ON GPIO_ResetBits(GPIOB,GPIO_Pin_5);
#define LED_OFF GPIO_SetBits(GPIOB,GPIO_Pin_5);
#define MAX 100 //最长的接收和发送数据大小
u8 RxBuffer[MAX]; //接收寄存数组
u8 TxBuffer[MAX]; //发送寄存数组
int RxCount=0; //接收发送字节数
int TxCount=0;
//LED的GPIO初始化,此处可以增加替换自己开发板的IO口
void GPIO_LED_init()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
GPIO_SetBits(GPIOB,GPIO_Pin_5); //默认关闭LED
}
//串口GPIO的初始化 GPIOA_PIN_9为TX,GPIOA_PIN_10为RX
void GPIO_USART_int()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; //TX为复用推挽输出模式
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING; //RX为输入悬空模式
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
}
//初始化串口1
void USART_init()
{
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
USART_InitStructure.USART_BaudRate=115200; //波特率为115200
USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;
USART_InitStructure.USART_Parity=USART_Parity_No;
USART_InitStructure.USART_StopBits=USART_StopBits_1;
USART_InitStructure.USART_WordLength=USART_WordLength_8b;
USART_Cmd(USART1,ENABLE);
USART_Init(USART1,&USART_InitStructure);
}
//查询法发送一字节
char USART1_SendByte(u8 data)
{
int cnt = 0;
USART_SendData(USART1,data); //发送数据
while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET) //如果发送失败返回0
{
cnt++;
if(cnt>12000)
return 0;
}
return 1;
}
//查询法接收一字符
u8 USART1_GetByte()
{
while(USART_GetFlagStatus(USART1,USART_FLAG_RXNE)==RESET){} //等待接收完成
return (USART_ReceiveData(USART1));
}
u8 ReceiveData()
{
vu32 cnt=0;
while(1)
{
RxBuffer[RxCount++]=USART1_GetByte();
if(strstr((char *)RxBuffer,"ON")!=NULL) //对比串口接收到的字符串,为ON就返回1
{
RxCount=0;
return 1;
}
else
if(strstr((char *)RxBuffer,"OFF")!=NULL) //对比窗口接收到的字符串,为OFF就返回2
{
RxCount=0;
return 2;
}
else
if(RxCount>3) //如果未接收到ON或OFF则重新接收并返回0
{
RxCount=0;
return 0;
}
}
}
void SendString(u8 *state) //用来向串口调试助手发送字符串
{
while(*state!='