unity3D和串口通信,接收下位機數據和發送指令

public class SerialCommunication : MonoBehaviour
{
    public GUIText gui;
    public string portName = "COM2";
    public int baudRate = 9600;
    public Parity parity = Parity.None;
    public int dataBits = 8;
    public StopBits stopBits = StopBits.One;


    int[] data = new int[6];//用於存儲6位數據
    SerialPort sp = null;
    Thread dataReceiveThread;
    //發送
    string message = "";
    //byte[] message=new byte[8];
    void Start()
    {
        OpenPort();
        dataReceiveThread = new Thread(new ThreadStart(DataReceiveFunction));
        dataReceiveThread.Start();
    }


    void Update()
    {
        string str = "";
        for (int i = 0; i < data.Length; i++)
        {
            str += data[i].ToString() + " ";
        }
        gui.text = str;
        Debug.Log(str);
    }


    public void OpenPort()
    {
        sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
        sp.ReadTimeout = 400;
        try
        {
            sp.Open();
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }


    public void ClosePort()
    {
        try
        {
            sp.Close();
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }


    public void WriteData(string dataStr)
    {
        if (sp.IsOpen)
        {
            sp.Write(dataStr);
        }


    }
    void OnApplicationQuit()
    {
        ClosePort();
    }

    void DataReceiveFunction()
    {
        byte[] buffer = new byte[128];
        int bytes = 0;
        int flag0 = 0xFF;
        int flag1 = 0xAA;
        int index = 0;//用於記錄此時的數據次序
        while (true)
        {
            if (sp != null && sp.IsOpen)
            {
                try
                {
                    bytes = sp.Read(buffer, 0, buffer.Length);
                    for (int i = 0; i < bytes; i++)
                    {


                        if (buffer[i] == flag0 || buffer[i] == flag1)
                        {
                            index = 0;//次序歸0 
                            continue;
                        }
                        else
                        {
                            if (index >= data.Length) index = data.Length - 1;//理論上不應該會進入此判斷,但是由於傳輸的誤碼,導致數據的丟失,使得標誌位與數據個數出錯
                            data[index] = buffer[i];//將數據存入data中
                            index++;
                        }


                    }
                }
                catch (Exception ex)
                {
                    if (ex.GetType() != typeof(ThreadAbortException))
                    {
                        Debug.Log(ex.Message);
                    }
                }
            }
            Thread.Sleep(10);
        }
    }




    void OnGUI()
    {
        message = GUILayout.TextField(message);
        if (GUILayout.Button("Send Message"))
        {
            WriteData(message);
        }
        string by = "XX AA 03 31 20 51 00 00";
        if (GUILayout.Button("Send", GUILayout.Height(50), GUILayout.Width(100)))
        {
            WriteData(by);
        }
    }


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