本文介绍了以字符串形式接收数字(uart)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 uart 接收一个打包为字符串的数字.我正在发送数字 1000,所以我得到 4 个字节 + 空字符.但是当我使用 atoi() 将数组转换为数字并将整数与 1000 进行比较时,我并不总是得到正确的数字.这是我接收号码的中断处理函数.可能有什么问题?

I'm trying to receive a number through uart which is packed as a string. I'm sending number 1000, so I get 4 bytes + null character. But when I convert the array to number with atoi() and compare the integer with 1000 I don't always get a correct number. This is my interrupt handler function for receiving the number. What could be wrong?

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);
    }
}

推荐答案

试试这个代码.在这里我检查最大接收字节数以避免缓冲区溢出(和可能的硬件故障).我创建了一个特定的函数来清除接收缓冲区.您还可以找到字符串长度的定义,因为代码更灵活.我还建议检查接收错误(在读取传入字节后),因为如果出现错误,接收将被阻止.

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;
}

这篇关于以字符串形式接收数字(uart)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:13