C
C#2y ago
JoJoCa

Serial reading

I use this code to read the values my arduino reads, and I use that in unity. However the datareceive event never triggers.
public class NewBehaviourScript : MonoBehaviour
{
public string recievedData;
public GameObject cube;
Vector3 rotationVal;
SerialPort microcontroller = new SerialPort("COM4");
void Start()
{


microcontroller.BaudRate = 9600;
microcontroller.Parity = Parity.None;
microcontroller.StopBits = StopBits.One;
microcontroller.DataBits = 8;
microcontroller.Handshake = Handshake.None;
microcontroller.RtsEnable = true;
microcontroller.DtrEnable = true;
microcontroller.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

microcontroller.Open();


}

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{

SerialPort sp = (SerialPort)sender;
Debug.Log("Recieving");
string data = sp.ReadLine();
rotationVal = new Vector3(0, float.Parse(data), 0);
}

void Update()
{
cube.transform.eulerAngles = rotationVal;
}

}
public class NewBehaviourScript : MonoBehaviour
{
public string recievedData;
public GameObject cube;
Vector3 rotationVal;
SerialPort microcontroller = new SerialPort("COM4");
void Start()
{


microcontroller.BaudRate = 9600;
microcontroller.Parity = Parity.None;
microcontroller.StopBits = StopBits.One;
microcontroller.DataBits = 8;
microcontroller.Handshake = Handshake.None;
microcontroller.RtsEnable = true;
microcontroller.DtrEnable = true;
microcontroller.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

microcontroller.Open();


}

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{

SerialPort sp = (SerialPort)sender;
Debug.Log("Recieving");
string data = sp.ReadLine();
rotationVal = new Vector3(0, float.Parse(data), 0);
}

void Update()
{
cube.transform.eulerAngles = rotationVal;
}

}
I've also tried just doing a Readline in the update method, which worked but it took about 30 seconds or more before my code read the changes my arduino received.
0 Replies
No replies yetBe the first to reply to this messageJoin