A. stm32 串口中斷發送和接收怎麼回事,就是串口的中斷方式和查詢方式有什麼區別
使用中斷接收發送方式,可隨時響應串口的接收發送請求,提高串口響應時間;
在程序上操作步驟如下:
首先:在void RCC_Configuration(void)中配置好串口時鍾;及在void GPIO_Configuration(void)配置好管腳;
RCC_PCLK2Config(RCC_HCLK_Div1); //串口波特率的確定
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA||RCC_APB2Periph_USART1, ENABLE);
/* Configure USART1 RTS (PA12) and USART1 Tx (PA9) as alternate function push-pull 根據資料可查得各管腳對應*/
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //推挽輸出
GPIO_Init(GPIOA, &GPIO_InitStructure);
其次:在 void NVIC_Configuration(void)函數中使能串口中斷;
/* Enable the USART1 Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQChannel; //通道設置為串口1中斷(故後面應選擇在「void USART1_IRQHandler(void)」開中斷)
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //中斷佔先等級0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //中斷響應優先順序0
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //打開中斷
NVIC_Init(&NVIC_InitStructure);
其次。配置好串口,並開中斷
/* Enable the USART1 Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQChannel; //通道設置為串口1中斷(故後面應選擇在「void USART1_IRQHandler(void)」開中斷)
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //中斷佔先等級0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //中斷響應優先順序0
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //打開中斷
NVIC_Init(&NVIC_InitStructure);
最後,可在stm32f10x_.it.c中的void USART1_IRQHandler(void)函數里寫上串口中斷發生時中斷服務函數即可;
u8 RX_dat; //定義字元變數
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //判斷發生接收中斷
{
RX_dat=(USART_ReceiveData(USART1) & 0x7F); //接收數據,整理除去前兩位
USART_ClearITPendingBit(USART1, USART_IT_RXNE); //清除中斷標志
while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET){}//等待接收結束
// USART_ITConfig(USART1, USART_IT_RXNE, DISABLE); //關中斷
USART_SendData(USART1,RX_dat); //發送數據
}
程序實現功能:當有數據通過串口發送過來時,程序進入串口中斷服務程序,在中斷服務程序中發送接收到的數據;