简体   繁体   English

Com Port C ++读取0xFF

[英]Com Port C++ read 0xFF

I'm trying to read/write from a com port. 我正在尝试从com端口读取/写入。 When I open the Com Port I make it Non overlapped. 当我打开通讯端口时,我将其设置为非重叠。 Everything works fine, but when I read a 0xFF byte it sees it like an EOF and finishes the read. 一切正常,但是当我读取一个0xFF字节时,它看起来像是EOF并完成了读取。 Can I make a Non overlapped read 0xFF? 我可以使非重叠读取为0xFF吗?

Here is my code: 这是我的代码:

//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++; } }

It seems that your char is signed (its signedness is implementation-dependent), so 0xFF is -1 . 看来您的char已签名(其签名取决于实现),因此0xFF -1

Use unsigned char to represent "bytes". 使用unsigned char表示“字节”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM