2015-09-20 82 views
1

我試圖通過作爲字符串打包的uart接收一個數字。我發送數字1000,所以我得到4個字節+空字符。但是當我使用atoi()將數組轉換爲數字並將整數與1000進行比較時,我並不總是得到正確的數字。這是我接收號碼的中斷處理函數。有人有任何想法,有什麼可能是錯的?作爲字符串(uart)的接收號碼

void USART1_IRQHandler(void) 
{ 
    if(USART_GetITStatus(USART1, USART_IT_RXNE)) 
    { 
     char t = USART1->RDR; 
     if((t != '\n' && t!='\0') && (cnt < 4)) 
     { 
      received_string[cnt] = t; 
      cnt++; 
     } 
     else 
     { 
      cnt = 0; 
     } 

     t = 0; 
     received_string[4] = 0; 
    } 

    if(cnt==4) 
    { 
     data = atoi(received_string); 
    } 
} 
+2

您需要調試您的代碼。檢查收到的字符以及組成該字符串的內容。 *「我並不總是得到一個正確的數字。」* - 這是一個不完整的觀察,並且表明您在調試時沒有多少努力。 – sawdust

+0

是的,你真的需要在RX緩衝區中發送原始字節(received_string數組)。您可能會發送'\ r \ n'或其他東西,而不僅僅是\ n,這與串行終端程序很相似。 – rost0031

回答

0

請試試此代碼。在這裏,我檢查接收到的最大字節數以避免緩衝區溢出(以及可能的硬件故障)。我創建了一個特定的函數來清除接收緩衝區。您還可以找到字符串長度的定義,因爲代碼更加靈活。我還建議檢查接收錯誤(在讀取傳入字節後),因爲如果發生錯誤,接收將被阻止。

//Define the max lenght for the string 
#define MAX_LEN 5 

//Received byte counter 
unsigned char cnt=0; 

//Clear reception buffer (you can use also memset) 
void clearRXBuffer(void); 

//Define the string with the max lenght 
char received_string[MAX_LEN]; 

void USART1_IRQHandler(void) 
{ 
    if(USART_GetITStatus(USART1, USART_IT_RXNE)) 
    { 
     //Read incoming data. This clear USART_IT_RXNE 
     char t = USART1->RDR; 

     //Normally here you should check serial error! 
     //[...] 

     //Put the received char in the buffer 
     received_string[cnt++] = t;  

     //Check for buffer overflow : this is important to avoid 
     //possible hardware fault!!! 
     if(cnt > MAX_LEN) 
     { 
      //Clear received buffer and counter 
      clearRXBuffer();     
      return; 
     } 

     //Check for string length (4 char + '\0') 
     if(cnt == MAX_LEN) 
     { 
      //Check if the received string has the terminator in the correct position 
      if(received_string[4]== '\0'){ 

       //Do something with your buffer 
       int data = atoi(received_string); 
      } 

      //Clear received buffer and counter 
      clearRXBuffer();     
     } 
    } 
} 

//Clear reception buffer (you can use also memset) 
void clearRXBuffer(void){ 
    int i; 
    for(i=0;i<MAX_LEN;i++) received_string[i]=0; 
    cnt=0; 
}