【问题标题】:Receiving number as string (uart)接收数字作为字符串(uart)
【发布时间】:2015-12-17 04:44:46
【问题描述】:

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

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

【问题讨论】:

  • 你需要调试你的代码。检查接收到的字符,以及组成字符串的内容。 “我并不总是得到正确的数字。” -- 这是一个不完整的观察,表明您在调试方面付出的努力很少。
  • 是的,您确实需要在 RX 缓冲区(received_string 数组)中发布您看到的原始字节。您可能会发送\r\n 或其他内容,而不是像串行终端程序常见的\n

标签: string serial-port stm32 uart


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    相关资源
    最近更新 更多