When I try to read from a serial port (uart) in Linux on an RaspberryPi I always get a CPU load of 5-10% when in a loop. As SerialPorts should be blocking, this shouldn't use that much cpu load, or am I wrong?
I tried two codes:
Simple Code
var port = new SerialPort("/dev/ttyUSB0", 57600);
port.Open();
while (true)
{
if (port.BytesToRead > 0)
{
while (port.BytesToRead > 0)
Console.Write($"{port.ReadByte().ToString("X2")} ");
Console.WriteLine("");
}
Thread.Sleep(100);
}
Advanced Code
static int blockLimit = 100;
static void Main(string[] args)
{
var port = new SerialPort("/dev/ttyUSB0", 57600);
port.Open();
byte[] buffer = new byte[blockLimit];
Action kickoffRead = null;
kickoffRead = delegate
{
port.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate (IAsyncResult ar)
{
try
{
int actualLength = port.BaseStream.EndRead(ar);
byte[] received = new byte[actualLength];
Buffer.BlockCopy(buffer, 0, received, 0, actualLength);
raiseAppSerialDataEvent(received);
}
catch (IOException exc)
{
handleAppSerialError(exc);
}
kickoffRead();
}, null);
};
kickoffRead();
while (true)
Thread.Sleep(1000);
}
private static void handleAppSerialError(IOException exc)
{
throw new NotImplementedException();
}
private static void raiseAppSerialDataEvent(byte[] received)
{
Console.WriteLine(BitConverter.ToString(received));
}
Both with the same result: Two processes which uses together 5% to 10% cpu load
Using .NET Core 3.0 Preview 2
and System.IO.Ports 4.6.0-preview-19073.11
on a RaspberryPi 3b+
running with HypriotOS 1.10.0