Serial communication is essential thing in Embedded communication. .NET Micro Framework comes with SerialPort class in Microsoft.SPOT.Hardware namespace. Unfortunately Micro Framework 2.5 lacks some useful features for sending and receiving strings over serial port.

SerialPortEx Class

I wrote extended version of SerialPort class, that brings few more methods comparing to original one. Here is the “interface”:

public class SerialPortEx : IDisposable
    private SerialPort port;
    public SerialPortEx(SerialPort.Configuration configuration)

    public SerialPortEx(SerialPort.Serial comPort, SerialPort.BaudRate speed, bool flowControl)
        : this(new SerialPort.Configuration(comPort, speed, flowControl))

    public void Write(byte[] buffer, int offset, int count)
    public void Write(string text)
    public void WriteLine(string text)
    public int Read(byte[] buffer, int offset, int count, int timeout)
    public int Read(byte[] buffer, int offset, int count)
    public string ReadLine()
    public string ReadTo(string value)

    public void Flush()
    public void Dispose()

    public System.Text.Encoding Encoding;
    public string NewLine;
    public int ReadTimeout;

String operations

Main motivation for me, was to add the ReadLine() method. This methods reads a string in given Encoding from serial port, up to NewLine value. By default the NewLine is set to Line Feed = 0x0A = \n , but it can be changed to anything else.

All reading operations uses the ReadTimeout property, which is by default set to the System.Threading.Timeout.Infinite value. If operation timeouts then returns null.

Where to get it?

Here comes the full listing of SerialPortEx class. Feel free to use it and improve it. If you will add some interesting improvements let me know.

Download: SerialPortEx.cs [9 Kb]

Updated 25. April 2008: Correct reading of 2-bytes characters.