0

我有一台 Windows 机器连接到一台运行 Debian 的单板计算机,我正在尝试使用串行端口在它们之间来回发送字节。在 Windows 端,我的代码如下所示:

// open serial port
HANDLE hSerial;
hSerial = CreateFile ("COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

// get serial parameters
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength = sizeof (dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams)) {
    cout << "error getting state\n";
    exit(0);
}

// set serial params
dcbSerialParams.BaudRate = CBR_115200;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity   = NOPARITY;
if (!SetCommState (hSerial, &dcbSerialParams)) {
    cout << "error setting parameters\n";
    exit(0);
}

// set time outs
COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 10;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 10;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts (hSerial, &timeouts)) {
    cout << "problem setting timeout values\n";
    exit(0);
} else cout << "timeouts set\n";

unsigned char temp = 0;

bool keepReading = true;
while (keepReading) {
    DWORD dwBytesRead = 0;
    ReadFile (hSerial, &temp, 1, &dwBytesRead, NULL);
    if (1 == dwBytesRead) cout << (unsigned int) temp << " ";
    if (255 == temp) keepReading = false;
}
cout << endl;

bool keepWriting = true;
unsigned char send = 0;
while (keepWriting) {
    DWORD dwBytesWritten = 0;
    WriteFile (hSerial, &send, 1, &dwBytesWritten, NULL);
    if (255 == send) keepWriting = false;
    send++;
}

在 Linux 方面,我有:

int fd = open("/dev/ttymxc0", O_RDWR | O_NOCTTY);
struct termios options;
bzero (options, sizeof(options));
options.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
options.c_iflat = IGNPAR;
options.c_oflag = 0;
options.c_lflag = ICANON;
options.c_cc[VMIN] = 1;
options.c_CC[VTIME] = 0;
tcflush (fd, TCIFLUSH);
tcsetattr (fd, ICSANOW, &options);

bool keepWriting = true;
unsigned char send = 0;
while (keepWriting) {
    write (fd, &send, 1);
    if (255 == send) keepWriting = false;
    send++;       
}

bool keepReading = true;
while (keepReading) {
    unsigned char temp = 0;
    int n = read (fd, &temp, 1);
    if (-1 == n) {
        perror ("Read error");
        keepReading = false;
    } else if (1 == n) {
        cout << temp << " ";
    }
    if (255 == temp) keepReading = false;

}
cout << endl;

当我在两端运行代码时,第一组 while 循环工作正常,windows 机器显示 0 到 255。第二组从不运行,linux 端read函数返回 0,表示端口关闭,windows 端报告它已写入所有请求的字节。这里发生了什么?

4

0 回答 0