Serial port in C# is very useful for interfacing Arduino or other microcontrollers systems with a PC. Most of these ones communicate with computers using a FTDI chip, or an equivalent converting a serial port to a virtual USB Communication Device Class (CDC).
As explained by Ben Voigt in his excellent article “If you must use a .NET system.IO.Ports.SerialPort”, C# implementation of the serial port is not reliable at all. Let’s focus on different tested situations in order to have an idea of what is working and not.
In Winform applications, SerialPort available from the ToolBox is working in most tested situations, including using DataReceived event and BytesToRead function in order to know how many bytes are available in the reception buffer.
In WPF applications, SerialPort doesn’t work anymore, event if it has the same attributes and methods ! More precisely, DataReceived event will trigger only when a few characters are sent, including ‘0x0A’ (‘\n’). If you don’t send this “special” byte, the event will not trigger. Also, if you try to read periodicaly the number of bytes available on the serial port, BytesToRead will always return 0. Whatever the settings of the SerialPort are, data will be transmitted only upon the arrival of a special character.
The behaviour makes the System.IO.Ports.SerialPort impossible to use.
A solution for getting a reliable solution is to use the WinAPI serial port accessed through BaseStream. An example of implementation of a SerialPort named OptimizedSerialPort is proposed here. At the openning of the serial port, a continous read function is started, raising an event (DataReceived) containing received bytes (in e.Data) when some bytes arrive into the reception buffer.
Code is available for download here :
– Download library for .NET 6