![](/img/trans.png)
[英]How to fix problem with unity to arduino serial communication via Serial port
[英]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();
}
}
更新:
現在,您可以使用Microsoft .net開源框架而不是統一的默認框架,那里的串行通信就像一個魅力。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.