- Home /
Problems With Sending Data through Serial Port
I am currently working on a project that communicates between Arduino and Unity through the serial port. I got sending data to unity working great but when I try to send data from unity to Arduino with Serial port.WriteLine it keeps giving me the error, "IOException: The semaphore timeout period has expired." This error seems to freeze all data sent to Arduino because when I stop the game, all the commands get through to the Arduino at the same time. It also is not large amounts of data so I don't know why I would have bus space issues. Only 2 digit numbers.
you should post your code you use to communicate between the two - but a simplified version. Remove all the unnecessary code.
O$$anonymous$$ here is the code for Arduino that reads the data inside void loop. (I also already attach edservo1 in the setup function.)
if(Serial.available() > 0)
{
String incom$$anonymous$$gByte = Serial.readString();
int data = incom$$anonymous$$gByte.toInt();
servo1.write(data);
delay(64);
}
and this is the Unity code that sends the data:
using UnityEngine;
using System.Collections;
using System.IO.Ports;
public class Arduino : $$anonymous$$onoBehaviour
{
public SerialPort sp;
public GameObject hand;
float timer = 0;
void Start()
{
sp = new SerialPort("CO$$anonymous$$6", 9600, Parity.None, 8, StopBits.One);
sp.DtrEnable = false;
sp.ReadTimeout = 1; //Shortest possible read time out.
sp.WriteTimeout = 1; //Shortest possible write time out.
sp.Open();
if (sp.IsOpen)
{
sp.Write("Hello World");
Debug.Log("Connection Successful!");
}
else
Debug.LogError("Serial port: " + sp.PortName + " is unavailable");
}
void Update()
{
int coord = $$anonymous$$athf.RoundToInt(-hand.gameObject.transform.rotation.x);
if(Time.deltaTime >= timer) //add delay to serial flow.
{
sp.WriteLine(coord.ToString());
timer = Time.deltaTime + 0.5f;
}
}
}
I am just trying to set a servo's position to the rotation of the gameobject "hand" in my scene.
Could it be that you're trying to send information too frequently? At what point are you sending the data? And have you tried re-uploading your sketch to the arduino?
No, because I have a delay set for the data so it only updates every .5 seconds. And yes I have tried reuploading the code.
Answer by itisieric · Jun 15, 2020 at 07:54 AM
Did you find a solution to this?
Yes, I raised the read/write timeout to something like 500 I think. Did it for me.
Also added "delay(10);" and "Serial.flush();" in the Arduino code after reading the inco$$anonymous$$g data from Unity but before sending new data if you have to send any to Unity.
Your answer
Follow this Question
Related Questions
Read in 2 Different Arduino Values 1 Answer
The Semaphore Timeout Period Has Expired 0 Answers
Need Help Connecting Arduino to Unity 0 Answers
Unity Arduino Communication Problem 0 Answers