C# 极简代码实现串口通信,功能超丰富
安装NuGet库
对项目右键单击,选择“管理NuGet程序包”。
搜索“BytesIO”,在列表中选择“STTech.BytesIO.Serial”串口通信库,在右边的详情面板中单击“安装”。
程序截图
事件监听
通过SerialClient可以监听串口的事件。
设计及实现
界面
控件排布及命名如图所示。
代码
主界面完整代码如下所示:
using STTech.BytesIO.Serial;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Test.BytesIO.Serial.Desktop
{
public partial class MainForm : Form
{
// 串口连接客户端
private SerialClient client;
public MainForm()
{
InitializeComponent();
// 创建串口通信客户端
client = new SerialClient();
// 向下拉选项框中添加所有串口名称
cbPort.Items.AddRange(client.GetPortNames());
// 监听连接成功事件
client.OnConnectedSuccessfully += Client_OnConnectedSuccessfully;
// 监听连接失败事件
client.OnConnectionFailed += Client_OnConnectionFailed;
// 监听断开连接事件
client.OnDisconnected += Client_OnDisconnected;
// 监听接收数据事件
client.OnDataReceived += Client_OnDataReceived;
// 监听发送数据事件
client.OnDataSent += Client_OnDataSent;
// 监听发生异常事件
client.OnExceptionOccurs += Client_OnExceptionOccurs;
}
private void Client_OnExceptionOccurs(object sender, STTech.BytesIO.Core.Entity.ExceptionOccursEventArgs e)
{
Print($"异常: {e.Exception.Message}");
}
private void Client_OnDataSent(object sender, STTech.BytesIO.Core.Entity.DataSentEventArgs e)
{
Print($"发送: {e.Data.ToHexCodeString()}({e.Data.EncodeToString()})");
}
private void Client_OnDataReceived(object sender, STTech.BytesIO.Core.Entity.DataReceivedEventArgs e)
{
Print($"接收: {e.Data.ToHexCodeString()}({e.Data.EncodeToString()})");
}
private void Client_OnDisconnected(object sender, STTech.BytesIO.Core.Entity.DisconnectedEventArgs e)
{
Print("断开连接");
}
private void Client_OnConnectionFailed(object sender, STTech.BytesIO.Core.Entity.ConnectionFailedEventArgs e)
{
Print("连接失败");
}
private void Client_OnConnectedSuccessfully(object sender, STTech.BytesIO.Core.Entity.ConnectedSuccessfullyEventArgs e)
{
Print("连接成功");
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(cbPort.Text))
{
return;
}
client.PortName = cbPort.Text;
client.Connect();
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
client.Disconnect();
}
private void btnSend_Click(object sender, EventArgs e)
{
client.Send(tbSend.Text.GetBytes());
}
/// <summary>
/// 打印日志
/// </summary>
/// <param name="msg"></param>
private void Print(string msg)
{
Invoke(new EventHandler(delegate
{
tbRecv.AppendText($"[{DateTime.Now.ToLongTimeString()}] {msg}\r\n");
}));
}
}
}
源码下载
如果无法调试运行也没有关系,我已经整理打包上传到了CSDN下载站提供0积分下载:
https://download.csdn.net/download/lgj123xj/85139168