C++ Windows API RS232串口通信 完整代码
时间: 2024-09-20 14:10:02 浏览: 31
C++ 串口通信 RS232 代码
4星 · 用户满意度95%
C++通过Windows API可以实现RS232串口通信,这是一种常见的串行通信方式,特别是在旧式硬件设备上。以下是一个简单的示例,展示了如何打开串口、设置参数以及发送和接收数据:
```cpp
#include <windows.h>
#include <winsock2.h>
#include <Commctrl.h>
// 串口常量定义
const char* portName = "COM1"; // 指定串口号,如COM1, COM2等
const DWORD baudRate = CBR_9600; // 波特率,例如9600bps
const DWORD dataBits = DATABITS_8; // 数据位数,8位
const DWORD stopBits = STOPBITS_1; // 停止位数,1位
const DWORD parity = NOPARITY; // 校验位,无校验
void setupSerial()
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
std::cerr << "Failed to initialize Winsock" << std::endl;
return;
}
DCB serialConfig;
HANDLE hComPort = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hComPort == INVALID_HANDLE_VALUE)
{
std::cerr << "Failed to open the serial port" << std::endl;
WSACleanup();
return;
}
memset(&serialConfig, 0, sizeof(DCB));
GetCommState(hComPort, &serialConfig);
serialConfig.BaudRate = baudRate;
serialConfig.ByteSize = dataBits;
serialConfig.StopBits = stopBits;
serialConfig.Parity = parity;
if (!SetCommState(hComPort, &serialConfig))
{
std::cerr << "Failed to set serial port configuration" << std::endl;
CloseHandle(hComPort);
WSACleanup();
return;
}
}
void sendData(char* message)
{
DWORD bytesSent = 0;
WriteFile(hComPort, message, strlen(message) + 1, &bytesSent, NULL);
if (bytesSent <= 0)
{
std::cerr << "Failed to send data" << std::endl;
}
}
void receiveData(char* buffer, DWORD maxLength)
{
DWORD bytesRead = 0;
ReadFile(hComPort, buffer, maxLength, &bytesRead, NULL);
if (bytesRead > 0)
{
buffer[bytesRead] = '\0'; // Add null terminator for processed string
std::cout << "Received: " << buffer << std::endl;
}
else
{
std::cerr << "No data received" << std::endl;
}
}
int main()
{
setupSerial();
// 发送数据示例
char transmitMessage[] = "Hello from C++!";
sendData(transmitMessage);
// 接收数据并处理
char receiveBuffer[256];
receiveData(receiveBuffer, sizeof(receiveBuffer));
CloseHandle(hComPort); // 关闭串口连接
WSACleanup(); // 清理Winsock库
return 0;
}
```
请注意,这只是一个基本示例,实际应用中可能需要添加错误处理和其他功能,比如超时设置和异常处理。
阅读全文