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

" + ex.Message + "
Exiting 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
}

}

Hey, I have experienced the same problem. Were you able to solve it?,Hey, I am experiencing the same problem. Were you able to solve it?

Hello,

have the same problem with Teensy 4.1. I can send data and read properly but when I try to send from Unity I get an error. I am not able to call ReadLine ()