简体   繁体   中英

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:

50AF000E0242020B0D00010150E5

as you can see, I got extra 'ffffff' and missed some '0'! And because of missed data, sometimes the 'af' changed to '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 . 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:

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. You should pad out the values to 2 hex digits instead.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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