2016-07-17 102 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); 
} 

,看看你是否關閉手柄,它的完成發送之前。