2016-07-17 105 views
1

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

我目前使用的代码如下。基本上唯一重要的部分是最后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; 
} 

回答

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

,看看你是否关闭手柄,它的完成发送之前。