Unity Serial.ReadLine() issue
So I'm having an Arduino send Serial.print()
out.
I'm having the strangest issue, maybe it's Unity permissions or OS Permissions (Linux)
So here's what happens.
When Unity calls Serial.ReadLine()
Unity will wait forever, basically hanging.
Thought it was permissions so I added
sudo adduser $USER $(stat --format="%G" /dev/ttyACM0 )
in CMD. Now the account on Linux has permissions, same issues arise.
Here's the strangest part, Unity will hang forever until I type this into CMD while it's hanging,
cat /dev/ttyACM0
Unity will now run and say Resource is being used
So I close CMD, and now Unity runs perfectly.
Unity reads and writes to the Arduino with no issues from here.
However, I have to go through this process every time I want to run the program from Run Unity -> Run CMD -> Close CMD.
Also, adding Serial.ReadTimeout = 100;
does not fix the issue.
Unity will run, but will never read and will forever timeout.
Only working solution is what I stated above so far.
using System.IO.Ports;
public class PlayerBar : MonoBehaviour
{
SerialPort stream = new SerialPort("/dev/ttyACM0", 9600);
void start()
{
stream.Open();
stream.WriteTimeout = 100;
}
void Update()
{
string value = "default";
value = stream.ReadLine();
}
}
Arduino code
Serial.print("Distance-");
Serial.print(distance);
Serial.print("\n");
EDIT: something I tried which was interesting.
if (stream.BytesToRead > 0)
{
Debug.Log("Open");
}
else
{
Debug.Log("Closed");
}
The Arduino is never sending bytes.
Not until I open CMD -> run the line -> close CMD
I think Serial.Open() isn't correctly opening the serial port.
Answer by zammle2009wtf · Nov 13, 2020 at 03:42 PM
I got some information from
https://forum.arduino.cc/index.php?topic=464481.0
apparently stream.DtrEnable = true;
&& stream.RtsEnable = true;
fixes this issue.
SerialPort stream;
void Start()
{
stream = new SerialPort("/dev/ttyACM0", 9600);
stream.WriteTimeout = 300;
stream.ReadTimeout = 5000;
stream.DtrEnable = true;
stream.RtsEnable = true;
stream.Open();
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613015637im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
long lag using unity remote and arduino uno 0 Answers
Recursive serialization error? 0 Answers
Unity-Arduino wifi Communication 0 Answers