2013-05-01 111 views
2

這就是我想要做的。我已經有一些功能,例如這一次將數據寫入到串行端口,它完美的作品:使用C++從Arduino讀取串行數據

bool WriteData(char *buffer, unsigned int nbChar) 
{ 
    DWORD bytesSend; 

    //Try to write the buffer on the Serial port 
    if(!WriteFile(hSerial, (void *)buffer, nbChar, &bytesSend, 0)) 
    { 
     return false; 
    } 
    else 
     return true; 
} 

的閱讀功能是這樣的:

int ReadData(char *buffer, unsigned int nbChar) 
{ 
//Number of bytes we'll have read 
DWORD bytesRead; 
//Number of bytes we'll really ask to read 
unsigned int toRead; 

ClearCommError(hSerial, NULL, &status); 
//Check if there is something to read 
if(status.cbInQue>0) 
{ 
    //If there is we check if there is enough data to read the required number 
    //of characters, if not we'll read only the available characters to prevent 
    //locking of the application. 
    if(status.cbInQue>nbChar) 
    { 
     toRead = nbChar; 
    } 
    else 
    { 
     toRead = status.cbInQue; 
    } 

    //Try to read the require number of chars, and return the number of read bytes on success 
    if(ReadFile(hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0) 
    { 
     return bytesRead; 
    } 

} 

//If nothing has been read, or that an error was detected return -1 
return -1; 

} 

而且不管我做什麼用arduino,這個函數總是返回-1,我甚至嘗試加載一個不斷寫入字符到串口的代碼,但沒有任何結果。

我從這裏得到的功能:http://playground.arduino.cc/Interfacing/CPPWindows

所以我的功能基本上是相同的。我只是將它們複製到我的代碼中,而不是將它們用作類對象,但不止它是相同的。

所以這是我的問題,我可以寫入數據到串口,但我無法讀取,我可以嘗試什麼?

+0

你的線路是什麼樣的,打開串口? GetLastError是什麼?你確定這個設備實際上是給你一些東西來閱讀嗎? – 2013-05-01 12:30:25

+0

@MatsPetersson hSerial =的CreateFile(wText, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); hSerial是一個定義爲HANDLE hSerial的變量。你是這個意思嗎? – MyUserIsThis 2013-05-01 12:32:35

+0

@MatsPetersson我不知道如何隔離問題發生的地方。如果我打開Arduino IDE的串行監視器,我可以看到設備正在發送數據。該程序也可以發送數據。問題在於閱讀它。變量:status.cbInQue是0,它應該是要讀取的字節數。 – MyUserIsThis 2013-05-01 12:34:07

回答

0

對於任何有興趣的人,我已經解決了它,這是一個愚蠢的錯誤。我編寫了Arduino,以便在發送任何內容之前等待串行輸入。計算機程序編寫並連續發送一行代碼,我猜i7比Atmel快......顯然這些數據需要一些時間。

添加睡眠(10);在從計算機上讀取端口之前已足以最終讀取數據。

感謝@Matts的幫助。