簡體   English   中英

Arduino-Unity串行通信

[英]Arduino - Unity Serial Communication

我將在Unity和Arduino之間進行基本通信。 我的問題是,當我開始從單位發送數據到arduino時,它工作正常。 但是當我開始從Arduino讀取串口時。 我收到訪問被拒絕的錯誤!

了解更多有關該問題的信息后,我找不到真正的原因。 我需要了解為什么會發生這種情況。

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

 public class Program : MonoBehaviour {

public SerialPort mySerialPort = new SerialPort("COM7", 9600);
public volatile float speed=0;
volatile bool isPassed = true;
GameObject cube ;
public GUIStyle style ;
//  int readInterval = 4;
//  int alreadyCounter = 0;
//  string rxString = "";

void Start () {
    isPassed = true;
    speed = 0;
    //mySerialPort.ReadTimeout = 25;
    mySerialPort.Parity = Parity.None;
    mySerialPort.StopBits = StopBits.One;
    mySerialPort.DataBits = 8;
    mySerialPort.DtrEnable = true;

    cube = GameObject.FindGameObjectWithTag ("cube");

    /*foreach(string str in SerialPort.GetPortNames())
    {
        Debug.Log(string.Format("Existing COM port: {0}", str));
    };
    */
    try{
    mySerialPort.Open();
    }catch(Exception ex)
    {
        print("Start Error Opening : " + ex.ToString());
    }

    /*
new Thread (delegate() {
        updateSpeed();
    }).Start();
     */

}

void OnGUI(){
    GUI.Box (new Rect(100,100,100,100),"Speed : " + speed , style);
}
// Update is called once per frame
void Update () {
    cube.transform.Rotate(Vector3.up * speed *Time.deltaTime);
    if (mySerialPort.IsOpen) {
        speed = float.Parse (mySerialPort.ReadLine ()); 
    } else {
        if(mySerialPort!= null)
        {
            mySerialPort.Close();
            mySerialPort.Open();
        }
    }

        /*if (isPassed == true) {
        new Thread(delegate() {
            if(mySerialPort.IsOpen) {
                updateSpeed();
                isPassed = false;
            } else {
                try {
                    mySerialPort.Close();
                    mySerialPort.Open();
                } catch (Exception ex) {
                    print("Update Error Opening : " + ex.ToString());
                }
            }
        }).Start();
    }*/

}

public void updateSpeed()
{
    while (true) {
        speed = float.Parse(mySerialPort.ReadLine ());
        print ("Speed = " + speed);
        Thread.Sleep (60);
        mySerialPort.BaseStream.Flush ();
    }
}

void OnDestroy () 
{
    mySerialPort.Close();
}

}

當您調用“ 關閉 ”時,將在MSDN頁面上讀取串行端口。 它還建議不要在關閉后立即嘗試重新打開它,因為它可能尚未關閉。

另外,由於將銷毀SerialPort,因此您必須創建一個新的。 我建議在尚未打開時不要在Update中關閉和打開該端口。 在“開始”中將其打開一次,然后在OnDestroy中將其關閉。

編輯
當您在其上調用“關閉”時,似乎不必創建新的SerialPort。 因此,可以在“等待一段時間”后重用它。

更新:

現在,您可以使用Microsoft .net開源框架而不是統一的默認框架,那里的串行通信就像一個魅力。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM