STM32

您所在的位置:网站首页 keil5串口实验 STM32

STM32

2023-08-25 08:29| 来源: 网络整理| 查看: 265

实现的功能

       1.电脑发送‘ON’

如果已是亮灯状态则返回‘the LED has been ON’

如果为熄灭状态则点亮LED并返回‘the LED is ON now’

2.电脑发送‘OFF’

如果已是熄灭状态则返回‘the LED has been OFF’如果为亮灯状态则关闭LED并返回‘the LED is OFF now’

 

 

最终效果

 

 

使用的芯片为STM32F103C8T6,LED连接在GPIOC的第13号引脚

 

LED和串口的初始化

#include #include #include #include #include #include #include //LED开关 #define LED_ON GPIO_ResetBits(GPIOC,GPIO_Pin_13); #define LED_OFF GPIO_SetBits(GPIOC,GPIO_Pin_13); #define MAX 100 //最长的接收和发送数据大小 u8 RxBuffer[MAX]; //接收寄存数组 u8 TxBuffer[MAX]; //发送寄存数组 int RxCount=0; //接收发送字节数 int TxCount=0; //LED的GPIO初始化 void GPIO_LED_init() { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE); GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Pin=GPIO_Pin_13; GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; GPIO_Init(GPIOC,&GPIO_InitStructure); GPIO_SetBits(GPIOC,GPIO_Pin_13); //默认关闭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); } 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) { 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!='\0') USART1_SendByte(*state++); } void EmptyRxBuffer(u8 len) //清空接收寄存数组 { u8 i; for(i=0;i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3