繁体   English   中英

从串口C ++ Windows读取字节

[英]Reading bytes from serial port C++ Windows

嘿,我正在尝试与我连接到我的Windows机器的xbees接口。 我能够在AT模式下通过协调器写入终端设备,并且可以看到流式传输到我的XCTU控制台的数据。 但是,我无法理解如何读取传入的数据。

我目前使用的代码如下。 基本上唯一关键的部分是最后5行左右(特别是读写文件行),但我要发布所有内容只是为了彻底。 如何通过com端口读取我发送给xbee的数据? 我发送的数据只是0x00-0x0F。

我想我误解了读取文件的功能。 我假设我发送到xbee的位存储在缓冲区中,而缓冲区一次只能读取一个。 那是对的吗? 或者我是否需要编写整个字节而不是读取可用的数据? 我很抱歉,如果我的火车令人困惑,我对串行通信还不熟悉。 任何帮助表示赞赏。

#include <cstdlib>
#include <windows.h>
#include <iostream>
using namespace std;

/*
 * 
 */
int main(int argc, char** argv) {
    int n = 8; // Amount of Bytes to Read
    HANDLE hSerial;
    HANDLE hSerial2;
    hSerial = CreateFile("COM3",GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);// dont need to GENERIC _ WRITE
    hSerial2 = CreateFile("COM4",GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);// dont need to GENERIC _ WRITE
    if(hSerial==INVALID_HANDLE_VALUE || hSerial2==INVALID_HANDLE_VALUE){
        if(GetLastError()==ERROR_FILE_NOT_FOUND){
//serial port does not exist. Inform user.
    cout << "Serial port error, does not exist" << endl;
    }
//some other error occurred. Inform user.
    cout << "Serial port probably in use" << endl;
    }

    DCB dcbSerialParams = {0};
    dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
    if (!GetCommState(hSerial, &dcbSerialParams)) {
        cout << "error getting state" << endl;
    }
    dcbSerialParams.BaudRate=CBR_9600;
    dcbSerialParams.ByteSize=8;
    dcbSerialParams.StopBits=ONESTOPBIT;
    dcbSerialParams.Parity=NOPARITY;
    if(!SetCommState(hSerial, &dcbSerialParams)){
        cout << "error setting serial port state" << endl;

    }

    COMMTIMEOUTS timeouts = {0};

    timeouts.ReadIntervalTimeout = 50;
    timeouts.ReadTotalTimeoutConstant = 50;
    timeouts.ReadTotalTimeoutMultiplier =10;
    timeouts.WriteTotalTimeoutConstant = 50;
    timeouts.WriteTotalTimeoutMultiplier = 10;

    if (!SetCommTimeouts(hSerial, &timeouts)){
        cout << "Error occurred" << endl;
    }

    DWORD dwBytesWritten = 0;
    DWORD dwBytesRead = 0;
    unsigned char oneChar;
    for (int i=0; i<16; i++)
        {
          oneChar=0x00+i;
          WriteFile(hSerial, (LPCVOID)&oneChar, 1, &dwBytesWritten, NULL);
          ReadFile (hSerial2, &oneChar, 1, &dwBytesRead, NULL); // what I tried to do, just outputs white space
        }

    CloseHandle(hSerial);



    return 0;
}

在你的陈述中:

ReadFile (hSerial2, &oneChar, 1, &dwBytesRead, NULL);

您需要检查dwBytesRead的值以查看是否实际读取了任何字节。 也许在连接的一端,你想要一个简单的程序每秒发送一个字节。 另一方面,您要检查可用字节并在它们进入时转储它们。

您的程序中可能发生的是您在短时间内填充出站串行缓冲区,没有等待足够长的时间来读取任何数据,然后退出循环并关闭串行端口,可能在它完成发送之前排队的数据。 例如,在CloseHandle()调用之前写入,您可以添加:

COMSTAT stat;

if (ClearCommError(hCom, NULL, &stat))
{
    printf("%u bytes in outbound queue\n", (unsigned int) stat.cbOutQue);
}

并查看在完成发送之前是否关闭手柄。

暂无
暂无

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

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