STM32使用中斷接收字符串,可重複接收,使用\r\n作爲接收結束的標誌(這裏也可以自己定義)。
主要代碼如下:
串口的函數
#include "stm32f10x.h"
#include "usart.h"
u8 rxbuff[125] = {0};//定義接收字符串的緩衝區,可以自定義大小
void uart_init(u32 bound)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //複用推輓輸出
GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA.9
//USART1_RX GPIOA.10初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空輸入
GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA.10
//Usart1 NVIC 配置
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//搶佔優先級3
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //子優先級3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitStructure); //根據指定的參數初始化VIC寄存器
//USART 初始化設置
USART_InitStructure.USART_BaudRate = bound;//串口波特率
USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字長爲8位數據格式
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); //初始化串口1
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//開啓串口接受中斷
USART_Cmd(USART1, ENABLE); //使能串口1
}
void uart_putc(char c)
{
while(USART_GetFlagStatus(USART1,USART_FLAG_TXE) == RESET);
USART_SendData(USART1,c);
USART_ClearFlag(USART1,USART_FLAG_TXE);
}
void uart1_puts(char *str)
{
while(*str)
{
uart_putc(*str);
str++;
}
}
void USART1_IRQHandler(void) //串口1中斷服務程序
{
u8 res;
static u8 index = 0;
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
res = USART_ReceiveData(USART1);
USART_SendData(USART1,res);
rxbuff[index] = res;
if(rxbuff[index] == '\n')
{
rxbuff[index] = '\0';//將\n字符清零
rxbuff[index-1] = '\0';//將\r字符清零
index = 0;//數組下標放到最前面
return ;//接收結束直接返回
}
index++;
}
}
測試程序:
#include "stm32f10x.h"
#include "delay.h"
#include "usart.h"
/*
可以在串口調試助手中不斷的發送新的字符串
單片機可以不斷的接收新的字符串,並顯示在串口調試助手上
*/
int main()
{
uart_init(115200);
delay_init();
while(1)
{
uart1_puts("%s\r\n",rxbuff);
delay_ms(1000);
}
}