简体   繁体   English

Arduino-Unity串行通信

[英]Arduino - Unity Serial Communication

I am going to make a basic communication between Unity and Arduino. 我将在Unity和Arduino之间进行基本通信。 The problem that i have is that when i start sending data from unity to arduino, it's working properly. 我的问题是,当我开始从单位发送数据到arduino时,它工作正常。 But when i start reading serial from Arduino. 但是当我开始从Arduino读取串口时。 I got Access denied error !!! 我收到访问被拒绝的错误!

After i read more about the issue, i can't find the real reason for that. 了解更多有关该问题的信息后,我找不到真正的原因。 I need to understand why something like that happens. 我需要了解为什么会发生这种情况。

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

}

When you call Close the SerialPort is disposed as you can read on the MSDN page. 当您调用“ 关闭 ”时,将在MSDN页面上读取串行端口。 It also suggest to not try to reopen it immediately after closing it as it might not be closed yet. 它还建议不要在关闭后立即尝试重新打开它,因为它可能尚未关闭。

Also since the SerialPort will be disposed you would have to create a new one. 另外,由于将销毁SerialPort,因此您必须创建一个新的。 I would suggest to not closing and opening the port in Update when it's not open yet. 我建议在尚未打开时不要在Update中关闭和打开该端口。 Open it once in Start and just close it in OnDestroy. 在“开始”中将其打开一次,然后在OnDestroy中将其关闭。

edit 编辑
It seems you don't have to create a new SerialPort when you called Close on it. 当您在其上调用“关闭”时,似乎不必创建新的SerialPort。 So it can be reused after "waiting some time" . 因此,可以在“等待一段时间”后重用它。

Update: 更新:

Now, you can use Microsoft .net open source framework instead of the unity default, the serial communication works like a charm there. 现在,您可以使用Microsoft .net开源框架而不是统一的默认框架,那里的串行通信就像一个魅力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM