写一个C++的串口程序
时间: 2023-10-23 08:09:55 浏览: 97
串口程序C++编写
5星 · 资源好评率100%
下面是一个简单的 C++ 串口程序,用于向串口发送字符串并接收来自串口的数据:
```c++
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HANDLE hSerial;
DCB dcbSerialParams = {0};
COMMTIMEOUTS timeouts = {0};
DWORD dwBytesWritten, dwBytesRead;
char szBuff[256];
// 打开串口
hSerial = CreateFile(
"COM1", // 串口名称
GENERIC_READ | GENERIC_WRITE, // 读写权限
0, // 共享模式
NULL, // 安全描述符
OPEN_EXISTING, // 打开已存在的串口
FILE_ATTRIBUTE_NORMAL, // 文件属性
NULL); // 模板文件句柄
if (hSerial == INVALID_HANDLE_VALUE) {
cerr << "Error: Unable to open serial port." << endl;
return 1;
}
// 设置串口参数
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams)) {
cerr << "Error: Unable to get serial parameters." << endl;
CloseHandle(hSerial);
return 1;
}
dcbSerialParams.BaudRate = CBR_9600; // 波特率
dcbSerialParams.ByteSize = 8; // 数据位
dcbSerialParams.StopBits = ONESTOPBIT; // 停止位
dcbSerialParams.Parity = NOPARITY; // 校验位
if (!SetCommState(hSerial, &dcbSerialParams)) {
cerr << "Error: Unable to set serial parameters." << endl;
CloseHandle(hSerial);
return 1;
}
// 设置串口超时时间
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts(hSerial, &timeouts)) {
cerr << "Error: Unable to set serial timeouts." << endl;
CloseHandle(hSerial);
return 1;
}
// 向串口发送数据
const char* szData = "Hello, serial port!";
if (!WriteFile(hSerial, szData, strlen(szData), &dwBytesWritten, NULL)) {
cerr << "Error: Unable to write to serial port." << endl;
CloseHandle(hSerial);
return 1;
}
// 从串口读取数据
if (!ReadFile(hSerial, szBuff, sizeof(szBuff), &dwBytesRead, NULL)) {
cerr << "Error: Unable to read from serial port." << endl;
CloseHandle(hSerial);
return 1;
}
szBuff[dwBytesRead] = '\0';
cout << "Received data: " << szBuff << endl;
// 关闭串口
CloseHandle(hSerial);
return 0;
}
```
注意:这个程序只是一个简单的演示,实际应用中需要进行更多的错误处理和异常情况的处理。
阅读全文