写一个STM32F103的UART中断接收
时间: 2023-11-22 20:52:41 浏览: 88
stm32的usart接收中断
好的,下面就是一个基本的STM32F103的UART中断接收的代码示例:
```c
#include "stm32f10x.h"
#define BUFFER_SIZE 64
volatile uint8_t rx_buffer[BUFFER_SIZE];
volatile uint8_t rx_head = 0;
volatile uint8_t rx_tail = 0;
void USART1_IRQHandler(void) {
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) {
rx_buffer[rx_head++] = USART_ReceiveData(USART1);
if (rx_head >= BUFFER_SIZE) {
rx_head = 0;
}
}
}
int main(void) {
// 初始化GPIO和USART
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
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);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
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(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_head != rx_tail) {
// 有数据接收
uint8_t data = rx_buffer[rx_tail++];
if (rx_tail >= BUFFER_SIZE) {
rx_tail = 0;
}
// 处理接收到的数据
}
}
}
```
上面的代码中,我们使用USART1来进行UART通信,同时开启了接收中断,并在中断处理函数中将接收到的数据存入了一个循环队列中。在主程序中,我们不断检查循环队列中是否有新的数据,并进行相应的处理。
阅读全文