C# 一台电脑对接多个串口通讯实例(电子天平称)
比如:我们在对接串口硬件时。实时获取硬件发送过来的数据、比如获取电子称发送过来的结果。我们程序需要获取。还有一种情况 是一台电脑对接多个串口设备情况下如何开发。
1.封装一个OpenSerialPort实体类
using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestGetUnitek { public class OpenSerialPort { private SerialPort Sp = new SerialPort(); public class SerialPortModel { /// <summary> /// 端口号 /// </summary> public string PortName { get; set; } /// <summary> /// 波特率 /// </summary> public int BaudRate { get; set; } /// <summary> /// 奇偶验证 /// </summary> public Parity Parity { get; set; } /// <summary> /// 停止位 /// </summary> public StopBits StopBits { get; set; } /// <summary> /// 数据位 /// </summary> public int DataBits { get; set; } } public OpenSerialPort(SerialPortModel entity) { //绑定对象信息 Sp.PortName = entity.PortName; Sp.BaudRate = entity.BaudRate; Sp.Parity = entity.Parity; Sp.StopBits = entity.StopBits; Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived); Sp.ReceivedBytesThreshold = 1; Sp.DataBits = entity.DataBits; } /// <summary> /// 打开端口 /// </summary> /// <returns></returns> public string Open() { try { Sp.Open(); return "1"; } catch (Exception a) { return a.Message; } } //实时获取数据 public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { System.Threading.Thread.Sleep(100);//延迟100接收 Byte[] reData = new byte[Sp.BytesToRead]; //获取 Sp.Read(reData, 0, reData.Length); string msg = Encoding.ASCII.GetString(reData); string ComName = Sp.PortName; //释放 Sp.DiscardInBuffer(); } //关闭端口 public string Close() { try { Sp.Close(); return "1"; } catch (Exception a) { return a.Message; } } } }
2.然后在执行的地方。通过对象列表去获取多台设备信息以及启动
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Drawing; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using static TestGetUnitek.OpenSerialPort; namespace TestGetUnitek { public partial class Form2 : Form { public Form2() { InitializeComponent(); } private DBSql db = new DBSql(ConfigurationManager.AppSettings["conn"], DbProviderType.SqlServer); private void button1_Click(object sender, EventArgs e) { DataTable dt = db.ExecuteDataTable("SELECT COM,baudRate,DataBits,Parity,StopBits FROM T_GPM_SerialPortConfig", null); List<OpenSerialPort> list = new List<OpenSerialPort>(); foreach (DataRow dr in dt.Rows) { SerialPortModel model = new SerialPortModel(); var COM = dr["COM"].ToString(); var BaudRate = dr["BaudRate"].ToString(); var _Parity = dr["Parity"].ToString(); var _StopBits = dr["StopBits"].ToString(); var DataBits = dr["DataBits"].ToString(); model.PortName = COM; model.BaudRate = Convert.ToInt32(BaudRate); if (_Parity == "0") { model.Parity = Parity.None; } else if (_Parity == "1") { model.Parity = Parity.Odd; } else if (_Parity == "2") { model.Parity = Parity.Even; } model.StopBits = StopBits.One; model.DataBits = Convert.ToInt32(DataBits); OpenSerialPort s = new OpenSerialPort(model); list.Add(s); } foreach(var item in list) { //Thread thread = new Thread(new ThreadStart());//创建线程 //thread.Start(); //启动线程 item.Open(); } button1.Enabled = false; } public void UpdateTextBox(string text) { this.textBox1.Text = text; } } }
可以实现1-多台设备运行。获取回来的结果业务在写OpenSerialPort类的Sp_DataReceived方法里面