串行端口接收的字节数比发送的多两个

时间:2018-12-16 17:19:56

标签: c serial-port

我的设置是这样的:一台旧的Windows XP计算机仍然具有真实的串行端口,而一台更新的Windows 7计算机使用USB串行适配器。我正在尝试运行如下所示的librs232示例:

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

#include "librs232/rs232.h"

unsigned int err(unsigned int e);
unsigned int rs232_simple_test(void);

unsigned int err(unsigned int e)
{
    printf("%s (%s)\n", rs232_strerror(e), errno > 0 ? strerror(errno) : "");
    return e;
}

unsigned int rs232_simple_test(void)
{
    unsigned int try = 0;
    unsigned int bytes = 0;
    unsigned char data[1];
    unsigned int ret = 0;
    struct rs232_port_t *p = NULL;

    p = rs232_init();
    if (p == NULL)
        return 1;

#ifdef WIN32
    rs232_set_device(p, "COM1");
#else
    rs232_set_device(p, "/dev/ttyUSB0");
#endif
    ret = rs232_open(p);
    if (ret) {
        rs232_end(p);
        return err(ret);
    }

    rs232_set_baud(p, RS232_BAUD_9600);
    printf("[*] port settings: %s\n", rs232_to_string(p));

    rs232_flush(p);
    while (try++ < 10) {
        printf("%02d. [*] read: ", try);
        data[0] = 0x00;
        ret = rs232_read_timeout(p, data, 1, &bytes, 1000);
        if (ret)
            err(ret);
        else
            printf("0x%02x len: %d\n", data[0], bytes);

        data[0] = 0x05;
        bytes = 0;
        printf("%02d. [*] write: ", try);
        ret = rs232_write_timeout(p, data, 1, &bytes, 1000);
        if (ret)
            err(ret);
        else
            printf("len: %d\n", bytes);
    }

    rs232_end(p);
    return 0;
}

int main()
{
    return rs232_simple_test();
}

此代码连续十次向COM1发送字符0x05。我在Win7机器上运行测试程序。但是,WinXP计算机上的输出是这样的:

0x05
0x05
0x05
0x05
0x05
0x05
0x05
0x05
0x05
0x0500fc

您可以看到在最后一次串行写入操作中,突然多了两个字节(0x00fc)。这是为什么?那两个人从哪里来?我不明白同样,上面显示的测试程序的输出清楚地表明仅发送了1个字节:

[*] port settings: device: COM1, baud: 9600, data bits: 8, parity: none, stop bits: 1, flow control: off
01. [*] read: timeout error (No such file or directory)
01. [*] write: len: 1
02. [*] read: timeout error (No such file or directory)
02. [*] write: len: 1
03. [*] read: timeout error (No such file or directory)
03. [*] write: len: 1
04. [*] read: timeout error (No such file or directory)
04. [*] write: len: 1
05. [*] read: timeout error (No such file or directory)
05. [*] write: len: 1
06. [*] read: timeout error (No such file or directory)
06. [*] write: len: 1
07. [*] read: timeout error (No such file or directory)
07. [*] write: len: 1
08. [*] read: timeout error (No such file or directory)
08. [*] write: len: 1
09. [*] read: timeout error (No such file or directory)
09. [*] write: len: 1
10. [*] read: timeout error (No such file or directory)
10. [*] write: len: 1

那么为什么在最后一次写入操作中3个字节到达WinXP PC?

我检查了两台机器上的波特率,数据位,奇偶校验,流控制和停止位设置是否相同,并且它们也与上述代码中设置的波特率(9600波特)匹配,所以我真的不知道那里怎么了这里的任何人都可以告诉更多信息吗?

0 个答案:

没有答案