0
我試圖從COM端口讀取/寫入。 當我打開Com端口時,我使它不重疊。 一切工作正常,但是當我讀取0xFF字節它看起來像EOF並完成讀取。 我可以做一個非重疊讀取0xFF嗎?COM端口C++讀取0xFF
這裏是我的代碼:
//Opening the com port:
hComm = CreateFile(s.c_str(), // COM PORT GENERIC_READ | GENERIC_WRITE, // 0, // exclusive access NULL, // no security OPEN_EXISTING, // must be a port 0 , // async i/o NULL); // //Port init: void initPort(int baud) { uart_baud = baud; DCB dcb; dcb.DCBlength = sizeof(DCB); GetCommState(hComm, &dcb); // read current config dcb.BaudRate = baud; dcb.ByteSize = 8; dcb.StopBits = ONESTOPBIT; dcb.Parity = NOPARITY; dcb.fParity = FALSE; SetCommState(hComm, &dcb); } //Reading:(PS: private: char rx_packet[1024]; int rx_size;) int readByte(int timeout) { COMMTIMEOUTS CommTimeOuts; CommTimeOuts.ReadIntervalTimeout = 1; CommTimeOuts.ReadTotalTimeoutMultiplier = timeout; CommTimeOuts.ReadTotalTimeoutConstant = 0; CommTimeOuts.WriteTotalTimeoutMultiplier = 0; CommTimeOuts.WriteTotalTimeoutConstant = 0; SetCommTimeouts(hComm, &CommTimeOuts); char byte; DWORD bytes = 0; if (ReadFile(hComm, &byte, 1, &bytes, NULL)) { return bytes == 1 ? byte : -1; } return -1; } void readPacket(void) { int data_read; bool first_read = true; rx_size = 0; DWORD dwEventMask; DWORD ERR = 0; if (!SetCommMask(hComm, EV_RXCHAR)) return; if (!WaitCommEvent(hComm, &dwEventMask, NULL)) return; while (rx_size < MAX_PACKET_SIZE) { data_read = readByte(first_read ? 200 : 50); first_read = false; if (data_read == -1)return; rx_packet[rx_size] = (char)data_read; rx_size++; } } //Writing port: bool writeByte(char byte) { DWORD bytes = 0; WriteFile(hComm, &byte, 1, &bytes, NULL); return bytes == 1 ? true : false; } void RvcCommUART::writePacket(BYTE *data , UINT16 size) { int tx_index = 0; while (tx_index < size) { if (writeByte(data[tx_index]) == false) return; tx_index++; } }
在FileRead函數中字節是接收字節,字節數是函數正在讀取的字節數......這是將它用作DWORD的方式;它讀取它的字節的值發送到readPacket –
這是問題,它工作時,我確實從char字節更改爲unsigned char字節,非常感謝你 –