Unity 串口發送十六進制byte消息

 

using UnityEngine;
using System;
using System.IO.Ports;
using UnityEngine.UI;

public class spSend : MonoBehaviour
{

    public SerialPort sp;  
/*    public Text text;*/
    static public byte[] strSend = new byte[3];
    void Start()
    {
        sp = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
        //串口初始化
        try
        {
            sp.Open();
            Debug.Log("成功打開");
            //text.text = "成功打開";
        }
        catch (Exception ex)
        {
            //text.text = ex.ToString();
            Debug.Log(ex);
        }
    }

    //關閉串口
    void OnApplicationQuit()
    {
        sp.Close();
        Application.Quit();
    }

    //發送
    public void SendData(byte[] data)
    {
        if (sp.IsOpen)
        {
            //text.text = data[0].ToString();
               sp.Write(data, 0, data.Length);
        }
    }
}

使用

    public void SendMsg(string s)
    {
        string msg =s;
        byte[] cmd = new byte[1024 * 1024 * 3];
        cmd = Convert16(msg);
        serialController.SendData(cmd);
    }
    private byte[] Convert16(string strText)
    {
        strText = strText.Replace(" ", "");
        byte[] bText = new byte[strText.Length / 2];
        for (int i = 0; i < strText.Length / 2; i++)
        {
            bText[i] = Convert.ToByte(Convert.ToInt32(strText.Substring(i * 2, 2), 16));
        }
        return bText;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章