串口中断接收文本数据实例,stm32f10x系列开发板
时间: 2024-02-03 13:03:18 浏览: 62
下面是一个使用stm32f10x系列开发板的串口中断接收文本数据的示例代码:
```c
#include "stm32f10x.h"
#include <stdio.h>
#define RX_BUFFER_SIZE 128
uint8_t rx_buffer[RX_BUFFER_SIZE];
uint8_t rx_index = 0;
volatile uint8_t rx_complete = 0;
void USART1_IRQHandler(void)
{
uint8_t data = USART1->DR;
if ((data == '\n') || (data == '\r')) {
rx_buffer[rx_index] = '\0';
rx_complete = 1;
rx_index = 0;
} else {
rx_buffer[rx_index] = data;
rx_index = (rx_index + 1) % RX_BUFFER_SIZE;
}
}
void USART1_Init(uint32_t baudrate)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
// USART1 Tx (PA9) as alternate function push-pull
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// USART1 Rx (PA10) as input floating
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// USART1 configuration
USART_InitStructure.USART_BaudRate = baudrate;
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);
// Enable USART1 interrupt
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);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); // Enable USART1 RX interrupt
}
int main(void)
{
USART1_Init(115200);
printf("Serial communication started.\n");
while (1) {
if (rx_complete) {
printf("Received data: %s\n", rx_buffer);
rx_complete = 0;
}
}
}
```
在以上代码中,我们使用USART1串口接收数据,并通过中断方式进行处理。当接收到一个字符时,如果该字符为换行符或回车符,则表示接收完整一条文本数据,将数据存入rx_buffer数组中,并将rx_complete标志位设为1。如果接收到的字符不是换行符或回车符,则将该字符存入rx_buffer数组中。在主循环中,我们检测rx_complete标志位是否为1,如果为1,则表示接收到完整一条文本数据,我们通过printf()函数打印该数据。
需要注意的是,在使用USART1之前,我们需要先对GPIO和USART进行初始化。在以上代码中,我们使用printf()函数进行输出,因此需要在工程中添加相应的库文件和初始化代码。
阅读全文