Arduino - Unity串行通信

时间:2014-11-12 09:48:32

标签: c# unity3d arduino lag serial-communication

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

}

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

更新:

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

相关问题