• UNITY3D串口通信

    2021/3/16??????點擊:

    UNITY3D串口通信例子


    using UnityEngine;
    using System.Collections;
    using System.IO;
    using System.IO.Ports;
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Text;//16進制轉(zhuǎn)換
     
    public class U3DSerial : MonoBehaviour
    {
     
        public string portName = "COM1";
        public int baudRate = 115200;
        public Parity parity = Parity.None;
        public int dataBits = 8;
        public StopBits stopBits = StopBits.One;
        SerialPort sp = null;       //串口的通信類
        byte[] data = new byte[128];  //用戶存儲6位數(shù)據(jù)    
        Thread dataReceiveThread;
     
        string message = "$";//發(fā)送
        string msg; //接收到的數(shù)據(jù)顯示在Label
        string tip;//提示串口是否打開
     
        string str1 = "";
        string str2 = "";
        ListliData = new List();
        string str = "";
        private bool shuJuZJ = false;
     
        void Start()
        {
            OpenPort();
            dataReceiveThread = new Thread(new ThreadStart(DataReceiveFunction));//開啟線程接收數(shù)據(jù)
            dataReceiveThread.Start();
        }
        void Update()
        {
            if (shuJuZJ)
            {
                CancelInvoke("XieCheng");//如果str還未接收完整DataReceiveFunction()扔在執(zhí)行,則快速終止調(diào)用
                shuJuZJ = false;
                Invoke("XieCheng", 0.1f);//可根據(jù)數(shù)據(jù)大小來定接收完整數(shù)據(jù)的時間
            }
        }
        public void OpenPort()  //打開串口
        {
            sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
            sp.ReadTimeout = 400;
            try
            {
                sp.Open();
                Debug.Log("串口已經(jīng)打開");
                tip= "串口已經(jīng)打開";
            }
            catch (Exception ex)
            {
                Debug.Log(ex.Message);
            }
        }
        public void ClosePort()         //關(guān)閉串口
        {
            try
            {
                sp.Close();
                Debug.Log("關(guān)閉串口");
                tip= "關(guān)閉串口";
            }
            catch (Exception ex)
            {
                Debug.Log(ex.Message);
            }
        }
        public void WriteData(string dataStr)//寫入數(shù)據(jù)
        {
            if (sp.IsOpen)
            {
                sp.Write(dataStr);
            }
        }
        void OnApplicationQuit()
        {
            ClosePort();
        }
        void DataReceiveFunction()
        {
            byte[] buffer = new byte[128];
            //string str = string.Empty;    //此處只執(zhí)行一次
            //int index = 0;
            int bytes;
            while (true)
            {
                if (sp != null && sp.IsOpen)      //  sp != null &&
                {
                    try
                    {
                        //這里面會執(zhí)行多次,以接收byte[]數(shù)據(jù)
                        bytes = sp.Read(buffer, 0, buffer.Length);
                        for (int i = 0; i < bytes; i++)
                        {
                            data[i] = buffer[i];        //將數(shù)據(jù)存入data
                            //str += data[i].ToString("X2") + "/";    //X表示16進制,2表示兩位數(shù)
                            //index++;
                        }
                        //Debug.Log("長度:" + bytes);
                        if (bytes == 1)
                        {
                            liData.Clear();//添加數(shù)據(jù)前,先清空泛型數(shù)組
                            str1 = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                            liData.Add(str1);
                        }
                        else
                        {
                            str2 = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                            liData.Add(str2);
                            str = "";
                            foreach (var i in liData)
                            {
                                str += i;
                            } 
                            shuJuZJ = true;
                        }
                    }
                    catch (Exception e)
                    {
                        if (e.GetType() != typeof(ThreadAbortException))
                        {
                            //Debug.Log(e.Message);
                        }
                    }
                }
                Thread.Sleep(1);
            }
        }
        void XieCheng()
        {
            Debug.Log("*終數(shù)據(jù):" + str);
            //這里接收到的數(shù)據(jù)str,進行處理
        }
        void OnGUI()        //按鈕發(fā)送數(shù)據(jù)
        {
            message = GUILayout.TextField(message);
            if (GUI.Button(new Rect(100, 100, 100, 30), "Send Message"))
            {
                WriteData(message);
            }
            string by = "AA";
            if (GUI.Button(new Rect(100, 150, 100, 30), "Send"))
            {
                WriteData(by);
            }
            GUILayout.Label(msg);
            if (GUI.Button(new Rect(100, 200, 100, 30), "Quit"))
            {
                Application.Quit();
            }
            GUILayout.Label(tip);
        }
    }