c语言,串口,stm32,根据串口输入的不同字符串,打印不同的信息
时间: 2023-05-13 12:06:08 浏览: 92
stm32 串口程序
5星 · 资源好评率100%
可以使用STM32的串口接收中断来实现该功能。首先需要在代码中定义一个接收缓冲区,用于存储串口接收到的数据。然后在串口接收中断中,将接收到的数据存储到接收缓冲区中。接着,根据接收到的字符串内容,使用条件语句来判断需要打印的信息,并将其发送到串口输出缓冲区中,最后通过串口发送中断将信息发送出去。以下是示例代码:
```c
#include "stm32f10x.h"
#define RX_BUF_SIZE 64
uint8_t rx_buf[RX_BUF_SIZE];
uint8_t rx_len = 0;
void USART1_IRQHandler(void)
{
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
uint8_t data = USART_ReceiveData(USART1);
if (rx_len < RX_BUF_SIZE)
{
rx_buf[rx_len++] = data;
}
}
}
void print_info(uint8_t* str)
{
if (strcmp(str, "hello") == 0)
{
printf("Hello World!\r\n");
}
else if (strcmp(str, "name") == 0)
{
printf("My name is C知道.\r\n");
}
else
{
printf("Unknown command.\r\n");
}
}
int main(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_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USART1, ENABLE);
while (1)
{
if (rx_len > 0)
{
print_info(rx_buf);
rx_len = 0;
}
}
}
```
阅读全文