最近調試STM32的串口接收時發現例程中只能接收一個字節
例程如下:
1 //初始化串口1 2 void uart_init(u32 bound){ 3 //GPIO端口設置 4 GPIO_InitTypeDef GPIO_InitStructure; 5 USART_InitTypeDef USART_InitStructure; 6 NVIC_InitTypeDef NVIC_InitStructure; 7 8 RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); //使能USART1,GPIOA時鍾 9 USART_DeInit(USART1); //復位串口1 10 //USART1_TX PA.9 11 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9 12 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; 13 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //復用推挽輸出 14 GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化PA9 15 16 //USART1_RX PA.10 17 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; 18 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空輸入 19 GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化PA10 20 21 //Usart1 NVIC 配置 22 23 NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; 24 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//搶占優先級3 25 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //子優先級3 26 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能 27 NVIC_Init(&NVIC_InitStructure); //根據指定的參數初始化VIC寄存器 28 29 //USART 初始化設置 30 31 USART_InitStructure.USART_BaudRate = bound;//一般設置為9600; 32 USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字長為8位數據格式 33 USART_InitStructure.USART_StopBits = USART_StopBits_1;//一個停止位 34 USART_InitStructure.USART_Parity = USART_Parity_No;//無奇偶校驗位 35 USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//無硬件數據流控制 36 USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //收發模式 37 38 USART_Init(USART1, &USART_InitStructure); //初始化串口 39 USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//開啟中斷 40 USART_Cmd(USART1, ENABLE); //使能串口 41 42 } 43 void USART1_IRQHandler(void) //串口1中斷服務程序 44 { 45 u8 Res; 46 if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //接收中斷(接收到的數據必須是0x0d 0x0a結尾) 47 { 48 //USART_ClearITPendingBit(USART1,USART_IT_RXNE); 49 Res =USART_ReceiveData(USART1);//(USART1->DR); //讀取接收到的數據 50 USART_RX_BUF[buf_index++]=Res; 51 52 } 53 54 } 55 56 57
這是較為普遍的源碼例程的寫法,用原子的版本改的。這本身沒問題,但是,一旦運行,就會發現,只能接收一個字節,后面的都會丟失,調了1天沒找到原因,一搜索發現很多類似的情況。
后來正准備改用DMA時偶然找到問題所在,就是這句:
24 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//搶占優先級3 25 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //子優先級3
改為
24 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1 ; 25 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
后問題解決。
注意,不要在中斷中執行發送接收過程,存在中斷嵌套的問題,會造成只執行一次的現象。