#include <iostream> #include <windows.h> #include <thread> class SerialPort { public: //构造函数,打开串口并设置参数 SerialPort(const char* portName) { hSerial = CreateFileA( portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hSerial == INVALID_HANDLE_VALUE) { std::cerr << "Error opening serial port\n"; exit(1); } // 初始化串口参数 DCB dcbSerialParams = { 0 }; COMMTIMEOUTS timeouts = { 0 }; dcbSerialParams.DCBlength = sizeof(dcbSerialParams); if (!GetCommState(hSerial, &dcbSerialParams)) { std::cerr << "Error getting serial port state\n"; CloseHandle(hSerial); exit(1); } // 设置串口参数 dcbSerialParams.BaudRate = CBR_115200; // 波特率为115200 dcbSerialParams.ByteSize = 8; // 数据位为8位 dcbSerialParams.StopBits = ONESTOPBIT; // 停止位为1位 dcbSerialParams.Parity = NOPARITY; // 无校验位 if (!SetCommState(hSerial, &dcbSerialParams)) { std::cerr << "Error setting serial port state\n"; CloseHandle(hSerial); exit(1); } // 设置超时时间 timeouts.ReadIntervalTimeout = 50; // 读取数据之间的间隔时间 timeouts.ReadTotalTimeoutConstant = 50; // 读取数据的固定超时时间 timeouts.ReadTotalTimeoutMultiplier = 10; // 读取数据的超时时间倍数 timeouts.WriteTotalTimeoutConstant = 50; // 写入数据的固定超时时间 timeouts.WriteTotalTimeoutMultiplier = 10; // 写入数据的超时时间倍数 if (!SetCommTimeouts(hSerial, &timeouts)) { std::cerr << "Error setting serial port timeouts\n"; CloseHandle(hSerial); exit(1); } } //析构函数,关闭串口 ~SerialPort() { CloseHandle(hSerial); } //向串口写入数据 bool write(const char* data) { DWORD bytes_written; if (!WriteFile(hSerial, data, strlen(data), &bytes_written, NULL)) { std::cerr << "Error writing to serial port\n"; return false; } return true; } //从串口读取数据 bool read(char* buffer, DWORD buffer_size, DWORD& bytes_read) { if (!ReadFile(hSerial, buffer, buffer_size, &bytes_read, NULL)) { std::cerr << "Error reading from serial port\n"; return false; } return true; } private: HANDLE hSerial; }; void receive_thread(SerialPort* serial) { char buffer[32]; DWORD bytes_read; while (true) { if (serial->read(buffer, sizeof(buffer), bytes_read)) { if (bytes_read > 0) { std::cout.write(buffer, bytes_read);// Print received data } } } } void send_thread(SerialPort* serial) { char input[32]; while (true) { std::cin.getline(input, sizeof(input)); if (serial->write(input)) { //std::cout << "Sent: " << input << std::endl; } } } int main() { SerialPort serial("COM7"); std::thread t1(receive_thread, &serial); std::thread t2(send_thread, &serial); t1.join(); t2.join(); return 0; }
标签:std,include,read,C++,buffer,串口,input,超级终端 From: https://www.cnblogs.com/lizhiqiang0204/p/17448516.html