Receiving number as string (uart)

旧时模样 提交于 2019-12-01 10:50:38

Try this code instead. Here I check the max number of received bytes to avoid buffer overflow (and possible hardware fault). I created a specific function to clear the reception buffer. You can find also a definition for the string length because the code is more flexible. I suggest also to check the reception errors (after read the incoming byte) because in case of errors the reception is blocked.

//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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!