unity3d通过串口接收Arduino数据

 

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()
    {
        
    }
}

 

 

 

 

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

posted @ 2024-09-01 00:16  西北逍遥  阅读(35)  评论(0编辑  收藏  举报