看板 C_and_CPP 關於我們 聯絡資訊
遇到的問題: 讀裝置回傳的字原本應該是create 但是有些字會重複幾次像是creaaate之類的 開發平台: Dev-C++ 有問題的code: #include <iostream> #include <windows.h> #include <conio.h> using namespace std; DWORD WINAPI ReadProc(LPVOID); HANDLE hCom; OVERLAPPED osRead = {0}; int main(void) { HANDLE ReadThread; DWORD dwError,dw; DCB PortDCB; COMMTIMEOUTS TimeOuts; hCom=CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); if(hCom == INVALID_HANDLE_VALUE) { dwError=GetLastError( ); cout << "Get Error: " << dwError; cout << "\n Create I/O file failed\n"; return 0; } if ( !SetupComm( hCom, 1024, 128 ) ) { dwError=GetLastError( ); cout << "Get Error: " << dwError; cout << "\n Set Comm buffer failed\n"; return 0; } TimeOuts.ReadIntervalTimeout=MAXDWORD; TimeOuts.ReadTotalTimeoutMultiplier=0; TimeOuts.ReadTotalTimeoutConstant=0; TimeOuts.WriteTotalTimeoutMultiplier=10; TimeOuts.WriteTotalTimeoutConstant=1000; if( !SetCommTimeouts(hCom, &TimeOuts) ) { dwError = GetLastError( ); cout << "Get Error: " << dwError; cout << "\n Set Timeout failed\n"; return 0; } GetCommState(hCom, &PortDCB); PortDCB.BaudRate = CBR_115200; PortDCB.ByteSize = 8; PortDCB.Parity = NOPARITY; PortDCB.StopBits = ONESTOPBIT; if( !SetCommState(hCom, &PortDCB) ) { dwError = GetLastError( ); cout << "Get Error: " << dwError; cout << "\n Set DCB failed\n"; return 0; } if ( !SetCommMask(hCom, EV_RXCHAR) ) { dwError = GetLastError( ); cout << "Get Error: " << dwError; cout << "\n SetCommMask failed\n"; return 0; } osRead.hEvent = CreateEvent(NULL, true, false, NULL); if ( osRead.hEvent == NULL ) { dwError = GetLastError( ); cout << "Get Error: " << dwError; cout << "\n Create Event failed\n"; return 0; } ReadThread = CreateThread(NULL, 0, ReadProc, NULL, 0, &dw); while( getch() != VK_ESCAPE ) { fflush(stdin); } CloseHandle(ReadThread); CloseHandle(hCom); return 0; } DWORD WINAPI ReadProc(LPVOID lpParam) { char Byte; DWORD CommEvent, dwByte, dwE; while(1) { if( WaitCommEvent(hCom, &CommEvent, NULL) ) { do { if ( ReadFile(hCom, &Byte, 1, &dwByte, &osRead) ) cout << Byte; } while (dwByte); } } return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.116.241.189
Dforce:已自解 多一個 if( dwByte > 0 ) cout << Byte; 08/20 13:11