Arduino - Unity串行通信

问题描述 投票:1回答:2

我将在Unity和Arduino之间进行基本的沟通。我遇到的问题是,当我开始将数据从unity发送到arduino时,它正常工作。但是当我开始从Arduino读取序列时。我得到Access拒绝错误!

在我阅读了更多关于这个问题之后,我找不到真正的原因。我需要理解为什么会发生类似的事情。

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

}
c# unity3d arduino lag serial-communication
2个回答
0
投票

当您调用Close时,您可以在MSDN页面上阅读SerialPort。它还建议在关闭它之后不要立即重新打开它,因为它可能尚未关闭。

此外,由于将丢弃SerialPort,您将不得不创建一个新的。 我建议不要在Update尚未打开时关闭并打开端口。在Start中打开它一次,然后在OnDestroy中关闭它。

编辑 当您调用Close时,您似乎不必创建新的SerialPort。所以它可以在"waiting some time"之后重复使用。


0
投票

更新:

现在,您可以使用Microsoft .net开源框架而不是统一默认,串行通信就像一个魅力。

© www.soinside.com 2019 - 2024. All rights reserved.