C++ WinAPI SerialPort 示例:创建简单串口通信程序
以下是用 C++、WinAPI 和 SerialPort 创建一个简单程序的示例代码:
#include <windows.h>
#include <iostream>
#include 'SerialPort.h' // SerialPort 类的头文件
using namespace std;
// 窗口过程函数
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 创建窗口
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = 'SerialPortExample';
wcex.hIconSm = LoadIcon(wcex.hInstance, IDI_APPLICATION);
if (!RegisterClassEx(&wcex))
{
MessageBox(NULL, '窗口类注册失败!', '错误', MB_ICONERROR);
return 0;
}
HWND hWnd = CreateWindow('SerialPortExample', 'SerialPort Example', WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 500, 300, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
MessageBox(NULL, '窗口创建失败!', '错误', MB_ICONERROR);
return 0;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// 创建 SerialPort 对象
SerialPort serialPort('COM3', 9600); // 创建 COM3 端口,波特率为 9600 的 SerialPort 对象
// 发送数据
string sendData = 'Hello, SerialPort!';
serialPort.write(sendData.c_str(), sendData.length());
// 接收数据
char receiveData[256];
int receiveLen = serialPort.read(receiveData, sizeof(receiveData));
if (receiveLen > 0)
{
receiveData[receiveLen] = '\0';
cout << '收到数据:' << receiveData << endl;
}
else
{
cout << '没有收到数据!' << endl;
}
// 消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
上述代码创建了一个带有一个窗口的程序,并在窗口程序中使用 SerialPort 类发送和接收数据。需要注意的是,在使用 SerialPort 类之前,需要将 SerialPort 类的头文件包含进来,并创建一个 SerialPort 对象。在本例中,创建了一个名为“COM3”的串口,并指定波特率为 9600。程序向串口发送了一个字符串,并尝试从串口接收数据。最后,程序进入消息循环,等待窗口消息。
原文地址: https://www.cveoy.top/t/topic/npqp 著作权归作者所有。请勿转载和采集!