2011-04-16 35 views
2

我在Windows上使用ReadFile()從串口讀取數據。這段代碼在某個時間點工作正常,但現在失敗了,我試圖找出問題的根源,所以我懷疑這是串行配置或超時問題,因爲沒有任何變化。ReadFile()表示失敗,但錯誤代碼爲ERROR_SUCCESS

ReadFile()返回false,表示發生錯誤。但是,當我立即檢查GetLastError()的值時,它返回0,即ERROR_SUCCESS。讀取的字節數是0,所以我傾向於認爲確實出錯了,但那個錯誤代碼完全沒用。

任何想法?謝謝。

編輯:這裏有一些相關的代碼片段:

#define GPS_COM_PORT L"COM3" 

// for reference, the device communicates at 115200 baud, 
// no parity, 1 stop bit, no flow control 

// open gps com port 
hGpsUart = CreateFile(GPS_COM_PORT, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); 
if (hGpsUart == INVALID_HANDLE_VALUE) 
{ 
    if (GetLastError() == ERROR_FILE_NOT_FOUND) 
    { 
     msg.setText("GPS COM port does not exist!"); 
     msg.exec(); 
     QApplication::quit(); 
    } 

    msg.setText("Error occurred while trying to open GPS COM port!"); 
    msg.exec(); 
    QApplication::quit(); 
} 

// set gps com port settings 
dcbSerialParams.DCBlength = sizeof(dcbSerialParams); 
if (!GetCommState(hGpsUart, &dcbSerialParams)) 
{ 
    msg.setText("Could not get GPS COM port settings!"); 
    msg.exec(); 
    QApplication::quit(); 
} 
dcbSerialParams.BaudRate = CBR_115200; 
dcbSerialParams.ByteSize = 8; 
dcbSerialParams.StopBits = ONESTOPBIT; 
dcbSerialParams.Parity = NOPARITY; 
if (!SetCommState(hGpsUart, &dcbSerialParams)) 
{ 
    msg.setText("Could not set GPS COM port settings!"); 
    msg.exec(); 
    QApplication::quit(); 
} 

// set gps com port timeouts 
timeouts.ReadIntervalTimeout = MAXDWORD; 
timeouts.ReadTotalTimeoutConstant = 0; 
timeouts.ReadTotalTimeoutMultiplier = 0; 
timeouts.WriteTotalTimeoutConstant = 50; 
timeouts.WriteTotalTimeoutMultiplier = 10; 
if (!SetCommTimeouts(hGpsUart, &timeouts)) 
{ 
    msg.setText("Could not set GPS COM port timeouts!"); 
    msg.exec(); 
    QApplication::quit(); 
} 

// ... later in the code ... 

char buf[161] = {0}; 
DWORD bytes_read = 0; 

// This returns false... 
if (!ReadFile(hGpsUart, buf, 160, &bytes_read, NULL)) 
{ 
    // Yet in here, GetLastError() returns ERROR_SUCCESS (0) 
    QMessageBox msg; 
    msg.setText("Error reading from GPS UART!"); 
    msg.exec(); 
} 
+0

你能發表一些你的代碼嗎? – 2011-04-16 07:45:35

+0

已發佈。感謝您的關注! – 2011-04-16 07:59:37

+0

不知道的人,對不起 – 2011-04-16 08:11:02

回答

2

我覺得關鍵是你的看法是你的來源,說短語「然而,在這裏,GetLastError()返回ERROR_SUCCESS(0)」

GetLastError的調用必須是在(可能)失敗調用之後進行的下一次Win32調用。作爲一個實驗,嘗試在失敗處理程序中顯式調用GetLastError(),但在消息框調用之前。我懷疑你會看到真實的失敗代碼。

祝你好運!

+0

賓果,那正是問題所在。 QMessageBox干擾了它。我現在可以看到正確的錯誤代碼,謝謝! – 2011-04-16 09:22:54

1

QMessageBox的構造函數可能會做一些清除GetLastError的事情。試試這個:

if (!ReadFile(hGpsUart, buf, 160, &bytes_read, NULL)) 
{ 
    int LastError = GetLastError() ; 
    QMessageBox msg; 
    msg.setText(QString("Error %1 reading from GPS UART!").arg(LastError)); 
    msg.exec(); 
} 
相關問題