我正在尝试从com端口读取/写入。
当我打开通讯端口时,我将其设置为非重叠。
一切正常,但是当我读取一个0xFF字节时,它看起来像是EOF并完成了读取。
我可以使非重叠读取为0xFF吗?
这是我的代码:
//打开com端口: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++; }}
最佳答案
您的char
似乎已签名(其签名取决于实现),因此0xFF
是-1
。
使用unsigned char
表示“字节”。
关于c++ - Com Port C++读取0xFF,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42931934/