虚拟串口基础读写例子,记录备忘
环境:win10 + mingw64
操作虚拟串口和物理串口的区别只是串口名称不同
,需要用个奇怪的写法,比如虚拟串口号为21:
char portName[] = "\\\\.\\COM21"
物理串口就可以直接写串口号,比如物理串口6:
char portName[] = "COM6"
不区分大小写,下面是一个示例程序:
#include <stdio.h>
#include <windows.h>
int main(int argc, char *argv[]) {
HANDLE hSerial;
DCB dcbSerialParams = {0};
COMMTIMEOUTS timeouts = {0};
//char portName[] = "COM6"; // 物理串口的设备路径,根据实际情况修改
char portName[] = "\\\\.\\COM21"; // 虚拟串口的设备路径,根据实际情况修改
char data[] = "Hello, Serial!"; // 待发送的数据
// 打开串口
hSerial = CreateFile(portName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hSerial == INVALID_HANDLE_VALUE)
{
printf("Failed to open serial port\n");
return 1;
}
// 配置串口参数
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams))
{
printf("Failed to get current serial parameters\n");
CloseHandle(hSerial);
return 1;
}
dcbSerialParams.BaudRate = CBR_115200; // 波特率
dcbSerialParams.ByteSize = 8; // 数据位数
dcbSerialParams.StopBits = ONESTOPBIT; // 停止位
dcbSerialParams.Parity = NOPARITY; // 校验位
if (!SetCommState(hSerial, &dcbSerialParams))
{
printf("Failed to set serial parameters\n");
CloseHandle(hSerial);
return 1;
}
// 配置读取超时
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts(hSerial, &timeouts))
{
printf("Failed to set serial timeouts\n");
CloseHandle(hSerial);
return 1;
}
// 发送数据
DWORD bytesWritten;
if (!WriteFile(hSerial, data, sizeof(data), &bytesWritten, NULL))
{
printf("Failed to write to serial port\n");
CloseHandle(hSerial);
return 1;
}
printf("Sent %d bytes\n", bytesWritten);
// 读取数据
DWORD bytesRead;
char buffer[256];
if (!ReadFile(hSerial, buffer, sizeof(buffer), &bytesRead, NULL))
{
printf("Failed to read from serial port\n");
CloseHandle(hSerial);
return 1;
}
printf("Received %d bytes: %s\n", bytesRead, buffer);
// 关闭串口
CloseHandle(hSerial);
return 0;
}
测试可以成功收发,绑定的对应串口收到数据: