'Best practice for reading serial port in Unity3D version 2020.3.30f1?
I have a MCU that is sending data to serial port. I want Unity3D to read the data. So far, nothing I have found works and I'm looking for some help on getting Unity to read the serial port.
Expected behavior is for the serial data to be saved to a string in order to perform operations with the data contained.
At the moment, when I run the Unity editor everything is fine until I actually try to read the serial port. As soon as an attempt is made to read the serial port the Unity editor totally freezes. There are no error logs, no console errors within the editor (since it is frozen), and the editor does not respond to my inputs (clicks, scrolls, etc.).
The solution at this point is to open the task manager and end the task for the Unity editor.
My current implementation is utilizing threads, however, I'm looking for the best practice to read serial port. Perhaps coroutines? Anyway, here's what I have so far.
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.IO.Ports;
using UnityEngine;
public class Arduino_Read_Serial : MonoBehaviour
{
[Header("Settings")]
[SerializeField] private bool enableReadThread = false;
private SerialPort data_stream = new SerialPort("COM6", 115200);
[SerializeField] private string receivedString;
private Thread readThread;
void Start()
{
data_stream.WriteTimeout = 300;
data_stream.ReadTimeout = 5000;
data_stream.DtrEnable = true;
data_stream.RtsEnable = true;
data_stream.Open();
if (data_stream.IsOpen)
{
readThread = new Thread(ReadThread);
}
}
void Update()
{
if (enableReadThread && data_stream.IsOpen)
{
readThread.Start();
enableReadThread = false;
}
else
{
Debug.Log("Pulse...");
}
if (receivedString != "")
{
//readThread.
}
//string[] datas = receivedString.Split(',');
//Debug.Log(datas);
}
void ReadThread()
{
while (data_stream.IsOpen)
{
receivedString = data_stream.ReadLine();
}
}
public void OnApplicationQuit()
{
Debug.Log("Thread stopped...");
readThread.Abort();
}
}
Any insight on some best practices for reading the serial port in Unity would be supremely appreciated.
These are the answers I attempted to use but none of them are working:
[1] Unity Serial.ReadLine() issue
[2] https://answers.unity.com/questions/1696938/arduino-serial-delegate-help.html
[3] https://answers.unity.com/questions/1735855/unity-crashes-when-connecting-to-a-serial-port.html
[4] https://forum.unity.com/threads/cant-use-system-io-ports.141316/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
