keil5判断接受来的数据 代码
时间: 2023-09-09 16:14:34 浏览: 58
以下是使用Keil5判断接收到的数据的代码示例:
```
#include <stdio.h>
#include <stm32f4xx.h>
#include <stm32f4xx_usart.h>
#define USARTx USART2
void USART_Configuration(void)
{
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
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_Rx | USART_Mode_Tx;
USART_Init(USARTx, &USART_InitStructure);
USART_Cmd(USARTx, ENABLE);
}
int main()
{
USART_Configuration();
while (1)
{
while (USART_GetFlagStatus(USARTx, USART_FLAG_RXNE) == RESET);
uint8_t data = USART_ReceiveData(USARTx);
if (data == 'A')
{
printf("Received data: %c, it is the letter A\n", data);
}
else if (data == 'B')
{
printf("Received data: %c, it is the letter B\n", data);
}
else
{
printf("Received data: %c, it is not A or B\n", data);
}
}
}
```
这个示例代码与之前的代码类似,不同之处在于添加了判断接收到的数据的语句。当接收到的数据是字母'A'时,打印出"Received data: A, it is the letter A"。当接收到的数据是字母'B'时,打印出"Received data: B, it is the letter B"。否则,打印出"Received data: x, it is not A or B",其中'x'为接收到的数据。