简体   繁体   English

C++串口数据接收错误

[英]C++ Serial port data received incorrectly

The data that received from serial port, is not correct, and sometime changed!从串口接收到的数据,不正确,有时会发生变化!

  if (WaitCommEvent(hSerial, &eventMask, NULL))
{
    if (ReadFile(hSerial, &input, 14, &bytesRead, NULL) !=0)
    {
        for (int i = 0; i < sizeof(input); i++)
        {
            cout << hex <<(int)input[i]<<endl;
        }
    }
    else
    {
        cout << "error reading file\n";
    }
}
else
{
    cout << "error waiting for comm event\n";
}

the data is:数据是:

50
ffffffaf
0
e
2
42
2
b
d
0
1
1
50
ffffffe5

when I get the data with Pyserial the data is:当我使用 Pyserial 获取数据时,数据是:

50AF000E0242020B0D00010150E5

as you can see, I got extra 'ffffff' and missed some '0'!如您所见,我得到了额外的 'ffffff' 并错过了一些 '0'! And because of missed data, sometimes the 'af' changed to '2f'!由于丢失数据,有时“af”会变成“2f”!

Is there any wrong things with my code?我的代码有什么问题吗?

The problem is not with the data, the data itself is fine.问题不在于数据,数据本身没问题。 It is your printing of the data that is faulty.是您打印的数据有问题。

You are not taking into account that input is using a signed char type that gets sign-extended when assigned to a signed int .您没有考虑到input使用的是签名char类型,该类型在分配给签名int时会进行符号扩展 That is where the extra f s in ffffffaf are coming from when printing a char whose value is 0xaf , because the high bit is 1 and gets carried into the extended bits:这就是打印值为0xafcharffffffaf中额外f s 的0xaf ,因为高位为 1 并被带入扩展位:

0xAF       =                            10101111
0xFFFFFFAF = 11111111 11111111 11111111 10101111

On the other hand, unsigned values are zero-extended instead:另一方面,无符号值是零扩展的

0xAF       =                            10101111
0x000000AF = 00000000 00000000 00000000 10101111

You are also not taking into account that you are printing numeric values 0..15 using just 1 hex digit, so leading 0 hex digits are not being printed.您也没有考虑到您仅使用 1 个十六进制数字打印数值0..15 ,因此不会打印前导0十六进制数字。 You should pad out the values to 2 hex digits instead.您应该将这些值填充为 2 个十六进制数字。

Try this:尝试这个:

char input[...];
...
if (ReadFile(hSerial, &input, 14, &bytesRead, NULL))
{
    for (int i = 0; i < bytesRead; ++i)
    {
       cout << hex << setw(2) << setfill('0') << static_cast<int>(static_cast<unsigned char>(input[i])) << endl;
    }
}

If you change input to use unsigned char instead of char , then you can remove that one type-cast:如果您将input更改为使用unsigned char而不是char ,那么您可以删除该类型转换:

unsigned char input[...];
...
if (ReadFile(hSerial, &input, 14, &bytesRead, NULL))
{
    for (int i = 0; i < bytesRead; ++i)
    {
       cout << hex << setw(2) << setfill('0') << static_cast<int>(input[i]) << endl;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM