赞
踩
关于 Modbus 通信,这里不再多赘述,网上有很多教程讲的很详细,对于通信协议,推荐这个文章,Modbus+RTU标准通信协议可以较为详细的了解具体的通信协议
以下为我的代码实现,注释很详细,相信大家都能看明白
需要注意的是,System.IO.Ports命名空间需要再C# 4.X才能运行,报错需要再Play Setting中自行更改
5.5.0202 代码段更新
using UnityEngine; using System.IO.Ports; using System; using System.Collections.Generic; using System.Threading; /// <summary> /// 串口通信类,挂载至任意对象下即可使用,建议(Main Camera) /// </summary> public class PortControl : MonoBehaviour { #region 定义串口属性 //定义基本信息 public string portName;//串口名 public int baudRate = 9600;//波特率 public Parity parity = Parity.None;//效验位 public int dataBits = 8;//数据位 public StopBits stopBits = StopBits.One;//停止位 protected SerialPort sp = null; #endregion protected Thread dataReceiveThread; protected Thread dataProcessorThread; public List<byte> receive = new List<byte>(); //接收到的所有消息 protected List<byte> message = new List<byte>(); //接收的一条消息 protected static string[] text; //处理后的消息 protected bool sendState = false; //接收状态 protected bool readTextState = false; //读取状态 public bool ReadTextState { get { return readTextState; } } public bool SendState { get { return sendState; } } private void Awake() { dataReceiveThread = new Thread(new ThreadStart(DataReceiveFunction)); dataProcessorThread = new Thread(new ThreadStart(DataProcessor)); } void Update() { } #region 创建串口,并打开串口 public virtual void OpenPort() { //创建串口 sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits); sp.ReadTimeout = 400; try { sp.Open(); dataReceiveThread.Start(); dataProcessorThread.Start(); sendState = true; Debug.Log("串口开启!!!!"); } catch (Exception ex) { Debug.Log(ex.Message); } } #endregion #region 程序退出时关闭串口 private void OnApplicationQuit() { ClosePort(); } public void ClosePort() { try { sp.Close(); dataReceiveThread.Abort(); dataProcessorThread.Abort(); } catch (Exception ex) { Debug.Log(ex.Message); } } #endregion /// <summary> /// 数据处理 /// </summary> /// <returns></returns> public virtual void DataProcessor() { while (true) { if (receive.Count > 0) { if (receive[0] == id && readTextState == false) { if (receive.Count >= 3) { int index = 0; message.Add(receive[index++]); message.Add(receive[index++]); message.Add(receive[index++]); switch (message[1]) { case 0x01: case 0x03: int length = Convert.ToInt32(Convert.ToString(message[2], 10)); if (receive.Count >= length + 5) { while (index < length + 3) { message.Add(receive[index++]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。