I’m trying to use System.io.ports to communicate with arduino. This is my first time doing it without uniduino and actually writing the serial data out myself. It all works nicely until 30-100 seconds in Unity slows to about 2 fps. The lights on he aruino that show serial input and output both light up solid (should be quickly blinking while communicating) an no serial is actually getting through to the arduino.
I’m sending strings of data to control two motor controllers. Arduino code is looking for the first character L or R followed by an int followed by \n. All works fine while it actually runs.
using UnityEngine;
using System.Collections;
using System.IO.Ports;
public class ManualSerialControl : MonoBehaviour {
public SerialPort serial = new SerialPort ("COM3", 19200);
public float motorInterpSpeed = 1f;
public float leftCurrentSpeed, rightCurrentSpeed;
public bool controlWithArrows;
// Use this for initialization
void Start () {
InvokeRepeating("SendValues", .1f, .1f);
InvokeRepeating("PrintValues", .1f, .1f);
// Trying 100 for write timeout seemed to help but may have been coincidence
// It still froze after about 100 seconds
//serial.WriteTimeout = 100;
}
// Update is called once per frame
void Update () {
if (serial.IsOpen == false)
serial.Open();
if (Input.GetButtonDown("aButton") || Input.GetKeyDown("q"))
{
Debug.Log ("Resetting");
serial.Write("Reset\n");
}
InterpolateSpeeds();
}
void InterpolateSpeeds()
{
if (controlWithArrows) {
if (Input.GetKey("up"))
{
leftCurrentSpeed = Mathf.Lerp (leftCurrentSpeed, 1f, motorInterpSpeed * Time.deltaTime * 0.25f);
rightCurrentSpeed = Mathf.Lerp (rightCurrentSpeed, 1f, motorInterpSpeed * Time.deltaTime * 0.25f);
} else if (Input.GetKey("down")) {
leftCurrentSpeed = Mathf.Lerp (leftCurrentSpeed, -1f, motorInterpSpeed * Time.deltaTime * 0.25f);
rightCurrentSpeed = Mathf.Lerp (rightCurrentSpeed, -1f, motorInterpSpeed * Time.deltaTime * 0.25f);
}
} else {
leftCurrentSpeed = Mathf.Lerp (leftCurrentSpeed, Input.GetAxis ("leftVertical"), motorInterpSpeed * Time.deltaTime);
rightCurrentSpeed = Mathf.Lerp (rightCurrentSpeed, Input.GetAxis ("rightVertical"), motorInterpSpeed * Time.deltaTime);
}
}
void PrintValues()
{
Debug.Log ("leftCurrentSpeed: " + leftCurrentSpeed);
Debug.Log ("rightCurrentSpeed: " + rightCurrentSpeed);
}
void SendValues()
{
int mappedValLeft = Map (leftCurrentSpeed, 1f, -1f, 0f, 6400f);
int mappedValRight = Map (leftCurrentSpeed, 1f, -1f, 0f, 6400f);
serial.Write ("L" + mappedValLeft + "\n");
serial.Write ("R" + mappedValRight + "\n");
}
int Map(float value, float min1, float max1, float min2, float max2)
{
return (int)Mathf.Lerp (min2, max2, Mathf.InverseLerp(min1, max1, value));
}
}