Unity C# controls turning on and off lights through SerialPort communication

Please flexibly change related functions and parameter configurations according to your own project needs! ! !

using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
using System.Threading;

/// <summary>
/// 串口通讯协议接口管理类
/// </summary>
public class PortControl : SingletonLock<PortControl>
{
    #region 定义串口属性
    /// <summary>
    /// 端口
    /// </summary>
    public string portName = "COM6";
    /// <summary>
    /// 所有设备端口
    /// </summary>
    private string[] allPorts;
    /// <summary>
    /// 波特率
    /// </summary>
    public int baudRate = 9600;
    /// <summary>
    /// 奇偶性
    /// </summary>
    public Parity parity = Parity.None;
    /// <summary>
    /// 数据位
    /// </summary>
    public int dataBits = 8;
    /// <summary>
    /// 停止位
    /// </summary>
    public StopBits stopBits = StopBits.One;
    /// <summary>
    /// 用于存储6位数据
    /// </summary>
    int[] data = new int[6];
    /// <summary>
    /// 串口控制
    /// </summary>
    SerialPort sp = null;
   
    #endregion

    /// <summary>
    /// 初始化串口连接端口
    /// </summary>
    public void Init()
    {
        allPorts = SerialPort.GetPortNames();//这一步是动态获取目前计算机检测到的所有串口
        OpenPort();//打开串口
    }

    /// <summary>
    /// 开灯
    /// </summary>
    public void Open()
    {
        WriteData(StrToToHexByte("01 06 00 01 11 11 14 56"));
    }

    /// <summary>
    /// 关灯
    /// </summary>
    public void Close()
    {
        WriteData(StrToToHexByte("01 06 00 01 00 00 D8 0A"));
    }

    /// <summary>
    /// 打开串口
    /// </summary>
    public void OpenPort()
    {
        for (int i = 0; i < allPorts.Length; i++)
        {
            sp = new SerialPort(allPorts[i], baudRate, parity, dataBits, stopBits);
            sp.ReadTimeout = 400;//读串口延迟
            try
            {
                sp.Open();
                Debug.Log("打开成功");
            }
            catch (Exception ex)
            {
                Debug.LogError(ex.Message);
                Debug.Log("打开失败");
            }
        }
    }

    /// <summary>
    /// 发送数据
    /// </summary>
    /// <param name="bys"></param>
    public void WriteData(byte[] bys)
    {
        if (sp.IsOpen)
        {
            sp.Write(bys, 0, bys.Length);
        }
    }

    /// <summary>
    /// 关闭串口
    /// </summary>
    public void ClosePort()
    {
        try
        {
            sp.Close();
        }
        catch (Exception ex)
        {
            Debug.LogError(ex.Message);
        }
    }

    /// <summary>
    /// String 类型转换成Byte类型
    /// </summary>
    /// <param name="hexString"></param>
    /// <returns></returns>
    private byte[] StrToToHexByte(string hexString)
    {
        hexString = hexString.Replace(" ", "");
        if ((hexString.Length % 2) != 0)
            hexString += " ";
        byte[] returnBytes = new byte[hexString.Length / 2];
        for (int i = 0; i < returnBytes.Length; i++)
            returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        return returnBytes;
    }

    private IEnumerator Wirte(byte[] bsy)
    {
        yield return new WaitForSeconds(0.5f);
        WriteData(bsy);
    }

}

Reference blog link:Unity serial communication_dlx41179’s blog-CSDN blog

Guess you like

Origin blog.csdn.net/U3DCoder/article/details/122191316
Recommended