unity3d透過串列埠接收Arduino資料

西北逍遥發表於2024-09-01

unity3d透過串列埠接收Arduino資料

using System.Collections;
using System.Collections.Generic;
using UnityEngine;



using System.IO.Ports;
using System;
using System.Threading;
using System.Text;

using SimpleJSON;




public class SerialPortController2 : MonoBehaviour
{

    private SerialPort sp;
    private Thread receiveThread;  //用於接收訊息的執行緒
    public string portName = "COM4";//串列埠名,根據自己arduino板子的串列埠號寫
    public int baudRate = 9600;//波特率
    public Parity parity = Parity.None;//效驗位
    public int dataBits = 8;//資料位
    public StopBits stopBits = StopBits.One;//停止位

    private int lastZ = 0;
    //-1:下   0:停止    1:提升
    private int upOrDown = 0;
    //up:false   down:true;
    private int lastUpOrDown = 0;

    private void Awake()
    {
        OpenPort();
    }


    #region 建立串列埠,並開啟串列埠
    public void OpenPort()
    {
        //建立串列埠
        sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
        sp.ReadTimeout = 400;
        try
        {
            sp.Open();
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }
    #endregion
    #region 程式退出時關閉串列埠
    void OnApplicationQuit()
    {
        ClosePort();
    }

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

    // Start is called before the first frame update
    IEnumerator Start()
    {
        while (true)
        {
            if (this.sp != null && this.sp.IsOpen)
            {
                try
                {
                    //SerialPort讀取資料有多種方法,我這裡根據需要使用了ReadLine()
                    String strRec = sp.ReadLine();            
                    //Debug.Log("Receive From Serial: " + strRec);
                } 
                catch
                {
                    //continue;
                }

            // 等待一幀時間,以便讓Unity處理其它更新
            yield return null;
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

##################################

相關文章