c#如何实现串口通信读取数据

2024-10-28 12:27:00
推荐回答(2个)
回答1:

使用System.IO.Port.SerialPort类实现串口通信

System.IO.Port.SerialPort类介绍

System.IO.Port.SerialPort是.NET Framework提供的操作串行端口的类,里面提供了一些方法、属性和和事件供开发者调用操作串口。

调用流程

1. 直接调用SerialPort的静态方法GetPortNames()获取当前计算机的串行端口名称数组

2.根据串口名称,初始化SerialPort对象,设置参数,调用Open()方法打开串口

3.调用Write()方法发送数据

4.注册接收数据的监听,获取数据(或者另起线程循环读取接收数据,本文使用注册监听方式接收数据)    

具体代码实现

using System;  
using System.IO.Ports;  
using System.Text;

namespace PortControlDemo  
{
public class PortControlHelper
{
#region 字段/属性/委托
///


/// 串行端口对象
///

private SerialPort sp;

///
/// 串口接收数据委托
///

public delegate void ComReceiveDataHandler(string data);

public ComReceiveDataHandler OnComReceiveDataHandler = null;

///
/// 端口名称数组
///

public string[] PortNameArr { get; set; }

///
/// 串口通信开启状态
///

public bool PortState { get; set; } = false;

///
/// 编码类型
///

public Encoding EncodingType { get; set; } = Encoding.ASCII;
#endregion

#region 方法
public PortControlHelper()
{
PortNameArr = SerialPort.GetPortNames();
sp = new SerialPort();
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
}

///
/// 打开端口
///

/// 端口名称
/// 波特率
/// 数据位
/// 停止位
/// 超时时间
public void OpenPort(string portName , int boudRate = 115200, int dataBit = 8, int stopBit = 1, int timeout = 5000)
{
try
{
sp.PortName = portName;
sp.BaudRate = boudRate;
sp.DataBits = dataBit;
sp.StopBits = (StopBits)stopBit;
sp.ReadTimeout = timeout;
sp.Open();
PortState = true;
}
catch (Exception e)
{
throw e;
}
}

///
/// 关闭端口
///

public void ClosePort()
{
try
{
sp.Close();
PortState = false;
}
catch (Exception e)
{
throw e;
}
}

///
/// 发送数据
///

///
public void SendData(string sendData)
{
try
{
sp.Encoding = EncodingType;
sp.Write(sendData);
}
catch (Exception e)
{
throw e;
}
}

///
/// 接收数据回调用
///

///
///
private void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[sp.BytesToRead];
sp.Read(buffer, 0, buffer.Length);
string str = EncodingType.GetString(buffer);
if (OnComReceiveDataHandler != null)
{
OnComReceiveDataHandler(str);
}
}
#endregion
}  
}

View Code

三、编写Winform串口通信工具界面

界面预览

回答2:

可以给你做,简单的事情,做好程序打包发给你.如需要直接发私信