(5) 關閉串口
利用API函數關閉串口非常簡單,只需使用CreateFile函數返回的控制碼作為參數調用CloseHandle即可:BOOL CloseHandle( HANDLE hObject ); //關閉handle
實例
CString fport; HANDLE hCom; //開啟COM1 fport = _T("\\\\.\\COM1"); hCom= CreateFile(fport, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if(hCom==INVALID_HANDLE_VALUE) { fport = fport + _T(" CAN NOT OPEN HANDLE!"); AfxMessageBox(fport); } DCB dcb; dcb.fDtrControl = DTR_CONTROL_ENABLE; GetCommState(hCom,&dcb); SetupComm(hCom, 1600, 1600); COMMTIMEOUTS TimeOuts; TimeOuts.ReadIntervalTimeout = 0; TimeOuts.ReadTotalTimeoutMultiplier = 0; TimeOuts.ReadTotalTimeoutConstant = 50; TimeOuts.WriteTotalTimeoutMultiplier = 5 ; TimeOuts.WriteTotalTimeoutConstant = 50 ; SetCommTimeouts(hCom,&TimeOuts); SetCommMask(hCom, 0); SetCommMask(hCom, EV_RXCHAR); dcb.BaudRate=115200; //波特率為115200 dcb.ByteSize=8; //每字節有8位 dcb.Parity=NOPARITY; //無奇偶校驗位 dcb.StopBits=ONESTOPBIT ; //一個停止位 SetCommState(hCom,&dcb); PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); //看是要讀還是要寫 DWORD dcount = 100; char buf[1024]; char temp_buf[1024]; while(1) { BOOL bWriteStat; //寫資料至ComPort bWriteStat = ::WriteFile(hCom, buf, dcount, &dcount, NULL); //從ComPort讀資料 bWriteStat = ::ReadFile(hCom, temp_buf, 1024, &dcount, NULL); //如果讀寫失敗 if(!bWriteStat) { AfxMessageBox(_T("FAIL!")); break; } } CloseHandle( HANDLE hCom);
最後附上這一系列的reference: Win32串口编程
沒有留言:
張貼留言