//發送訊息
void Serial::Write(CString message){
//DWORD res;
DWORD factdatda = (DWORD)20;
//IsStop = false;
/*if (WriteFile(hCom, message, message.GetLength(), &factdatda, NULL)){
IsStop = TRUE;
PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
AllocConsole();
//_cprintf(message+"\r\n");
}
else{
AfxMessageBox("發送失敗");
}*/
char* data = (LPSTR)(LPCSTR)message;
OVERLAPPED m_osWrite;//建立Overlapped結構
m_osWrite.InternalHigh = 0;
m_osWrite.Offset = 0;
m_osWrite.OffsetHigh = 0;
COMSTAT ComStat;
DWORD dwErrorFlags;
BOOL bWriteStat;
m_osWrite.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);//初始化Overlapped結構
bWriteStat = WriteFile(hCom, data, factdatda, &factdatda, &m_osWrite);//異步寫串口
}
//關閉串口
void Serial::Close(){
CloseHandle(hCom);
}
void Serial::read(){
DWORD dwBytesRead = 1000;
char* str = new char[(int)dwBytesRead];
for (int t = 0; t <= (int)dwBytesRead - 1; t++) str[t] = 0;
COMSTAT ComStat;
DWORD dwErrorFlags;
OVERLAPPED m_osRead; //建立Overlapped結構
memset(&m_osRead, 0, sizeof(OVERLAPPED));
m_osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
ClearCommError(hCom, &dwErrorFlags, &ComStat);
dwBytesRead = min(dwBytesRead, (DWORD)ComStat.cbInQue);
if (!dwBytesRead){//如果緩沖區為空,那么這里就會回傳
AfxMessageBox("錯誤1");
return;
}
BOOL bReadStatus;
bReadStatus = ReadFile(hCom, str, dwBytesRead, &dwBytesRead, &m_osRead);//異步讀串口,讀取緩沖區的內容
if (!bReadStatus) {
AfxMessageBox("錯誤2");
return ;
}
AllocConsole();
if (dwBytesRead)_cprintf("串口接受到的內容為:%d\r\n%s\r\n", (int)dwBytesRead, str);//如果讀取出來的緩沖區的內容不為空,那么把讀取出來的內容發送出來
return ;
}
每次都提示緩沖區為空,也就是錯誤1,求大神解答
uj5u.com熱心網友回復:
ReadFile之前,應該WaitCommEvent。上網搜代碼吧。uj5u.com熱心網友回復:
對方設備是不是需要硬體握手?如果需要的話,代碼里需要設定RTS為高電位,這樣才能收到資料。轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/115450.html
標籤:基礎類
