RS-422/232串口访问函数

DWORD MonitorRsStatusWords(int wParam)//监视串口状态字线程,需用户创建 { MSG msg; bool b_run_or_stop = false;//监视线程是否启动 HANDLE hRsPort; HWND hWnd = (HWND)wParam; unsigned char tra[8]; unsigned char rec[8]; static int iFalgBmp=0; while (1) { if (b_run_or_stop)//如果启动监视 { for(int i=0; i<8; i++) { rec[i] = 0; tra[i] = 0; } //自发自收演示代码 tra[0] = 0xc0; tra[1] = 0x10 + iFalgBmp%100; tra[2] = 0x20 + iFalgBmp%36; tra[3] = 0x30 + iFalgBmp%10; tra[4] = 0x40 + iFalgBmp%11; iFalgBmp++; Serial_Send(hRsPort, tra, 8); Serial_Send(hRsPort, tra, 8); Sleep(100); Serial_Read(hRsPort, rec, 8); ::PostMessage(hWnd, STATUS_RECEIVED, 0, (LPARAM)rec); } if (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { switch (msg.message) { case WM_QUIT: ExitThread(422); case START_MONITORING://启动监视,用户自定义消息 b_run_or_stop = true; hRsPort= (HANDLE)msg.wParam; break; case STOP_MONITORING://暂停监视,用户自定义消息 b_run_or_stop = false; break; default: break; } } else Sleep(100); } return 10; }; HANDLE InitSerialPort(int nCh, DWORD BaudRate, BYTE Parity, int stopBit) { HANDLE hComPort=NULL; DCB dcb; char strChn[16]; COMMTIMEOUTS CommTimeOut; if (nCh < 10) sprintf(strChn, "COM%d", nCh); else sprintf(strChn, "////.//COM%d", nCh); hComPort = CreateFile(strChn, GENERIC_READ | GENERIC_WRITE, 0, // exclusive access NULL, // no security attrs OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, // FILE_FLAG_OVERLAPPED, // overlapped I/O NULL); CommTimeOut.ReadIntervalTimeout =100; CommTimeOut.ReadTotalTimeoutMultiplier = 100; CommTimeOut.ReadTotalTimeoutConstant = 100; CommTimeOut.WriteTotalTimeoutMultiplier = 100; CommTimeOut.WriteTotalTimeoutConstant = 100; SetCommTimeouts(hComPort, &CommTimeOut); dcb.DCBlength = sizeof(DCB); GetCommState(hComPort, &dcb); dcb.BaudRate = BaudRate; dcb.ByteSize = 8; dcb.Parity = Parity; dcb.StopBits = stopBit; SetCommState(hComPort, &dcb); return hComPort; } int Serial_Send(HANDLE hRsPort, unsigned char *str, DWORD count) { if (hRsPort==INVALID_HANDLE_VALUE) return 0; DWORD bytesWritten; WriteFile (hRsPort, str, count, &bytesWritten, NULL); return (int)bytesWritten; } int Serial_Read(HANDLE hRsPort, unsigned char *recbuf, int count) { if (hRsPort==INVALID_HANDLE_VALUE) return 0; DWORD bytesRead; ReadFile(hRsPort, recbuf, count, &bytesRead, NULL); return (int)bytesRead; }

你可能感兴趣的:(null,security,file,access,byte)