Unity串口通讯(单位指令或者多位指令)
这是我自己用的串口通讯,通过修改指令停止位来去修改自己所需要的指令位数
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Text;
using System.Threading;
using UnityEngine;
public class UnityPortControlZ : MonoBehaviour
{
//接收端口的名字
private string getPortName;
private int baudRate;
private Parity parity = Parity.None;
private int dataBits = 8;
private StopBits stopBits = StopBits.One;
SerialPort sp = null;
private string _data;
///
/// 指令停止位(多少位指令)
///
public int dataStop = 1;
private Thread tPort;
// Use this for initialization
void Start()
{
// OpenPort();
StartCoroutine(OpenPort0());
}
private void Update()
{
PortSignalControl();
}
bool IsRead = false;
/// <summary>
/// 串口信号控制
/// </summary>
private void PortSignalControl()
{
if (IsRead)
{
IsRead = false;
}
}
/// <summary>
/// 关闭串口
/// </summary>
public void ClosePort()
{
try
{
sp.Close();
tPort.Abort();
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
List<string> listReceive = new List<string>();
/// <summary>
/// 发送字符串的函数
/// </summary>
/// <param name="data">发送的字符串</param>
public void SendSerialPortData(string data)
{
if (sp.IsOpen)
{
try
{
sp.WriteLine(data);
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
}
/// <summary>
/// 打开串口的协程
/// </summary>
/// <returns></returns>
IEnumerator OpenPort0()
{
yield return new WaitForSeconds(0.1f);
OpenPort();
}
public bool OpenPort()
{
if (sp == null || sp.IsOpen == false)
{
try
{
//var portName = configTest.dic["串口"]["板卡端口"];
//var baudRate = int.Parse(configTest.dic["波特率"]["数值0"]);
sp = new SerialPort("COM3", int.Parse("9600"), Parity.None, 8, StopBits.One);
sp.ReadTimeout = 500;
sp.WriteTimeout = 500;
sp.Open();
tPort = new Thread(new ThreadStart(PortReceive));
tPort.IsBackground = true;
tPort.Start();
return true;
}
catch (Exception ex)
{
throw ex;
}
}
else
{
throw new Exception("串口已经打开");
}
}
/// <summary>
///接收串口信号函数
/// </summary>
void PortReceive()
{
listReceive.Clear();
Debug.Log("开始接收消息");
while (this.sp != null && this.sp.IsOpen)
{
Thread.Sleep(0);
try
{
byte addr = Convert.ToByte(sp.ReadByte());
var item = AsciiToString(addr);
listReceive.Add(item);
string outString = String.Empty;
for (int i = 0; i < listReceive.Count; i++)
{
outString += listReceive[i];
}
if (listReceive.Count== dataStop)
{
print(outString);
_data = outString;
IsRead = true;
listReceive.Clear();
}
}
catch
{
}
}
}
public string AsciiToString(int asciiCode)
{
if (asciiCode >= 0 && asciiCode <= 255)
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] byteArray = new byte[] { (byte)asciiCode };
string strCharacter = asciiEncoding.GetString(byteArray);
return (strCharacter);
}
else
{
throw new Exception("ASCII Code is not valid.");
}
}
/// <summary>
/// 当应用退出时关闭串口
/// </summary>
private void OnApplicationQuit()
{
ClosePort();
}
/// <summary>
/// 当物体销毁时关闭串口
/// </summary>
private void OnDisable()
{
ClosePort();
}
}