STM32 atoi和strtol有时会丢失前两位数字。

3

我正在读取通过RS485发送的值,这个值是编码器的数据。首先,我会检查它是否返回了E字符(表示编码器出现了错误)。如果没有,我会执行以下操作:

    *position = atoi( buffer ); 
    // Also tried *position = (s32) strtol(buffer,NULL,10);

缓冲区中的数值为4033536,位置被设置为33536。在这个函数中,这种情况不是每次都会发生,可能只有1000次中的1次,虽然我没有计算。如果重新设置程序计数器并再次执行该行失败,则返回相同结果,但重新启动调试器会导致该值正确转换。
我正在使用Keil uVision 4,这是一个使用STM32F103VET6和STM32F10库V2.0.1的自定义板。这个问题真的让我感到困惑,以前从未遇到过这样的情况,非常感谢任何帮助。
谢谢。
1个回答

1

由于没有人知道,所以我决定写自己的转换函数,虽然不是最理想的解决方案,但它起到了作用。

bool cdec2s32(char* text, s32 *destination)
{
    s32 tempResult = 0;
    char currentChar;
    u8 numDigits = 0;
    bool negative = FALSE;
    bool warning = FALSE;

    if(*text == '-')
    {
      negative = TRUE;
      text++;
    }

while(*text != 0x00 && *text != '\r') //while current character not null or carridge return
{
    numDigits++;
    if(*text >= '0' && *text <= '9')
    {
        currentChar = *text;
        currentChar -= '0';

        if((warning && ((currentChar > 7 && !negative) || currentChar > 8 && negative )) || numDigits > 10) // Check number not too large
        {
            tempResult = 2147483647;
            if(negative)
                tempResult *= -1;

            *destination = tempResult;
            return FALSE;
        }

        tempResult *= 10;
        tempResult += currentChar;
        text++;
        if(numDigits >= 9)
        {
            if(tempResult >= 214748364)
            {
                warning = TRUE; //Need to check next digit as close to limit
            }
        }
    }
    else if(*text == '.' || *text == ',')
    {
        break;
    }
    else
        return FALSE;
}
if(negative)
    tempResult *= -1;

*destination = tempResult;
return TRUE;

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接