发送方程序:
#include <iostream> #include <fstream> #include <string> #include <windows.h> using namespace std; int main() { ofstream outfile("output.txt"); if (!outfile) { cerr << "无法打开输出文件" << endl; return 1; } string message = "Hello, Serial Port!"; outfile << message; outfile.close(); HANDLE hComm = CreateFile("COM3", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hComm == INVALID_HANDLE_VALUE) { cerr << "无法打开串口" << endl; return 1; } DCB dcbSerialParams = { 0 }; dcbSerialParams.DCBlength = sizeof(dcbSerialParams); if (!GetCommState(hComm, &dcbSerialParams)) { cerr << "无法获取串口状态" << endl; CloseHandle(hComm); return 1; } dcbSerialParams.BaudRate = CBR_9600; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; if (!SetCommState(hComm, &dcbSerialParams)) { cerr << "无法设置串口参数" << endl; CloseHandle(hComm); return 1; } DWORD bytesWritten; if (!WriteFile(hComm, message.c_str(), message.size(), &bytesWritten, NULL)) { cerr << "无法写入数据" << endl; CloseHandle(hComm); return 1; } CloseHandle(hComm); return 0; }
接收方程序:
#include <iostream> #include <fstream> #include <string> #include <windows.h> using namespace std; int main() { ifstream infile("input.txt"); if (!infile) { cerr << "无法打开输入文件" << endl; return 1; } string message; getline(infile, message); infile.close(); HANDLE hComm = CreateFile("COM3", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hComm == INVALID_HANDLE_VALUE) { cerr << "无法打开串口" << endl; return 1; } DCB dcbSerialParams = { 0 }; dcbSerialParams.DCBlength = sizeof(dcbSerialParams); if (!GetCommState(hComm, &dcbSerialParams)) { cerr << "无法获取串口状态" << endl; CloseHandle(hComm); return 1; } dcbSerialParams.BaudRate = CBR_9600; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; if (!SetCommState(hComm, &dcbSerialParams)) { cerr << "无法设置串口参数" << endl; CloseHandle(hComm); return 1; } DWORD bytesRead; string receivedMessage; while (ReadFile(hComm, &receivedMessage[0], receivedMessage.size(), &bytesRead, NULL) && bytesRead > 0) { receivedMessage.resize(bytesRead); } cout << "接收到的数据: " << receivedMessage << endl; CloseHandle(hComm); return 0; }