下面是一个简单的串口收发通信的程序,使用了Windows API函数实现。程序发送了一个包含三个字符的字符串”111″,并且在接收到数据后将其打印到控制台上。
#include #include int main(){HANDLE hComm; // 串口句柄char comPort[] = "COM2"; // 串口名称char writeBuff[] = "111"; // 发送的数据DWORD bytesWritten, bytesRead; // 发送和接收的字节数char readBuff[100]; // 接收缓冲区// 打开串口hComm = CreateFile(comPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);if (hComm == INVALID_HANDLE_VALUE) {printf("Failed to open serial port %s\n", comPort);return 1;}// 配置串口DCB dcbSerialParams = {0};dcbSerialParams.DCBlength = sizeof(dcbSerialParams);if (!GetCommState(hComm, &dcbSerialParams)) {printf("Failed to get serial parameters\n");CloseHandle(hComm);return 1;}dcbSerialParams.BaudRate = CBR_115200;dcbSerialParams.ByteSize = 8;dcbSerialParams.StopBits = ONESTOPBIT;dcbSerialParams.Parity = NOPARITY;if (!SetCommState(hComm, &dcbSerialParams)) {printf("Failed to set serial parameters\n");CloseHandle(hComm);return 1;}// 发送数据if (!WriteFile(hComm, writeBuff, sizeof(writeBuff), &bytesWritten, NULL)) {printf("Failed to write to serial port\n");CloseHandle(hComm);return 1;}printf("Sent %d bytes: %s\n", bytesWritten, writeBuff);// 接收数据if (!ReadFile(hComm, readBuff, sizeof(readBuff), &bytesRead, NULL)) {printf("Failed to read from serial port\n");CloseHandle(hComm);return 1;}printf("Received %d bytes: %s\n", bytesRead, readBuff);// 关闭串口CloseHandle(hComm);return 0;}
该程序使用了Windows API中的CreateFile
、ReadFile
和WriteFile
等函数实现串口的打开、读写和关闭操作。需要注意的是,串口的配置参数需要在DCB
数据结构中进行设置,并且设置完参数之后需要使用SetCommState
函数将其应用到串口上。
可以下载虚拟串口助手与程序调试看看: Virtual Serial Port Driver 8.0、和 sscom5.13.1 (我用的是这两个,Virtual Serial Port Driver建立虚拟串口对(比如新建COM2、COM3),sscom可以和你建立的串口实现通信(比如sscom设置成COM3, 程序里面设置成COM2)),如图: