Search code examples
c#.netraspberry-piserial-port

How to safely write to SerialPort in .NET 6 on Raspberry Pi


I am trying to add some safety around serial communication in .NET 6, but when nothing is connected to the port (on my testbed), I cannot properly dispose the port as any calls to SerialPort.Close() or SerialPort.Dispose() hangs.

I've managed to reduce it to the following MRE, which I am running on a Raspberry Pi 4 with Raspberry Pi OS. I'm building my application as framework dependent and portable.

using System.IO.Ports;

var sp = new SerialPort("/dev/ttyAMA0", 38400)
{
    DataBits = 8,
    Parity = Parity.None,
    StopBits = StopBits.One,
    WriteTimeout = TimeSpan.FromSeconds(3).Seconds,
    ReadTimeout = TimeSpan.FromMilliseconds(30).Seconds
};

try
{
    sp.Open();
    sp.WriteLine("123");
}
catch (Exception) { }
finally
{
    Console.WriteLine("Closing");
    sp.Close(); //Hangs here
    Console.WriteLine("Closed");

    Console.ReadLine();
}

Is there anything I can do to avoid my application hanging?


Solution

  • As it turns out, Raspberry Pi 4 has reserved the main UART (/dev/ttyAMA0) for Bluetooth.

    I needed to use /dev/ttyS0 instead.

    Hope this helps someone out there in a similar pickle.