c++ - Com 端口 C++ 读取 0xFF

标签 c++

我正在尝试从 com 端口读取/写入。 当我打开 Com 端口时,我将其设置为非重叠。 一切正常,但是当我读取一个 0xFF 字节时,它会将其视为 EOF 并完成读取。 我可以做一个非重叠读取 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++; } }

最佳答案

看起来你的 char 是有符号的(它的符号是依赖于实现的),所以 0xFF -1.

使用unsigned char来表示“字节”。

关于c++ - Com 端口 C++ 读取 0xFF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931934/

相关文章:

c++ - 如何检查 vector 是否指向 C++ 中二维 vector 中的空 vector ?

c++ - 类和命名空间的区别?

c++ - 当我需要通过指针传递时(而不是通过引用传递)

c++ - enable_if 迭代器作为默认模板参数?

c++ - 管理在多个控制台窗口中运行的程序?

c++ - 由 csv 文件填充的结构化列表中的冒泡排序

C++ 对象生命周期分析

java - 为什么如果我们不使用 join() 多线程 C++ 程序会崩溃,而类似的 Java 程序不会

c++ - 单击按钮时将值增加 1 C++

c++ - boost 属性 write_json 不正确的行为