I am going to make a basic communication between Unity and Arduino. The problem that i have is that when i start sending data from unity to arduino, it's working properly. But when i start reading serial from 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();
}
}
Update:
Now, you can use Microsoft .net open source framework instead of the unity default, the serial communication works like a charm there.