- Home /
How to receive data from serial port via USB in Unity (able to send but not receive)
Hello, I'm working on a project and I need to receive data from the serial port via USB. I wrote some code and I was able to send data, but every time I try to receive it, Unity crashes or throws errors my way. The SendData(); method works fine, but every time I try to call RecieveData(); Unity crashes. Does anyone know the solution?
Code:
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks;
public class SerialCommunicationScript : MonoBehaviour { SerialPort port = new SerialPort("COM7", 9600);
[SerializeField] string str = "data";
private void Start()
{
SerialCommunication();
}
private void Update()
{
SendData();
RecieveData();
}
void SerialCommunication()
{
Debug.Log("*****************************");
Debug.Log("*Serial Port Emulator *");
Debug.Log("*****************************");
Debug.Log("");
try
{
port.Open(); // try-catch block, if port is already opened it throws exception
}
catch (System.Exception ex)
{
Debug.Log("Error opening serial\n" + ex.Message + "\nExiting program...");
return;
}
}
private void SendData()
{
Debug.Log("Sending: ");
port.WriteLine(str); // Send string over serial
System.Threading.Thread.Sleep(2000); // Wait 2 seconds in loop
}
private void RecieveData()
{
Debug.Log("Recieving: ");
string data = port.ReadLine();
Debug.Log(data);
System.Threading.Thread.Sleep(2000); // Wait 2 seconds in loop
}
}
Your answer
Follow this Question
Related Questions
Unity read raw HID data => Debug.Log( data ) 0 Answers
Is it possible to interact with a USB Drive? 0 Answers
Unity - IOException: SerialPort.Open() 0 Answers
send string to serial port on android 0 Answers
Access to serial port on Android device 6 Answers