- Home /
How to read two separate values from the same SerialPort?
I want to send the state of my left wheel encoders along with the state of my right wheel encoders at the same time. For example if my arduino serial.writes that the left wheel is in state 1 and my right wheel is in state 3, I want to read it in Unity. However since Unity is only reading from one USB port, it gets confused. What I tried to do is write a binary value in the arduino IDE. Example;
Value = B0101; //in binary
Serial.write(Value); // this is in arduino, basically the first two binary values represent the left encoders' (2 of them) HIGH or LOW state and the last two binary values represent the right encoders'(also 2 encoders) HIGH or LOW state.
I would like to know how I could read it in Unity so that a change in the first two bits means one thing and a change in the last two bits means another. Also, I tried to do it by writing two separate scripts in Mono, but I get a I/O Exception error. I believe unity can't read from the same port by two separate scripts at the same time. Correct me if I'm wrong, and do you have any solution suggestions?
Answer by Jashengmato · Nov 29, 2013 at 09:48 AM
Arduino side:
leftWheelState = 3;
rightWheelState = 2;
Serial.print(leftWheelState);
Serial.print(',');
Serial.println(rightWheelState);
Unity side:
using System.IO.Ports;
SerialPort port = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
port.Open();
// Check if port is open;
....
// add data receive delegate
port.DataReceived += DataReceivedHandler;
private void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string data = sp.ReadLine();
// substring here, and get data you want
}
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Realtime Multiplayer Plugin 2 Answers
Export GameObject to unity3d in runtime 1 Answer
Alpha Transparency Shader Issue 1 Answer