Serial port communication in c# – part 2

luca 29/10/2011 0

After having learned how to list serial ports in our personal computer, in this part 2 we’re going to use them…

The class we need to use to read and write to serial port is SerialPort, present in System.IO.Ports namespace.

It has different constructors, with a different number of parameters. The most complete of them has the following signature:

public SerialPort(
    string portName,
    int baudRate,
    Parity parity,
    int dataBits,
    StopBits stopBits

If we need to use serial port COM3, with a speed of 9600 baud, without parity bit, with data bits and 1 stop bit, we’re going to write the following code:

SerialPort serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);

(sometimes you’ll find the same parameters in a shorter form: 9600 8N1)
You have to define Parity and stopBits values using costants included in each object.

If specified serial port is not present or can’t be used, the constructor rises an IOException.

After having an instance of SerialPort object, you can call open() method to open the port.
That method could rise several exceptions (port is already in use by another program, it is already in open state, some parameters are incorrect…) and you can trap them with a try…catch block:

catch (Exception ex)
    Console.WriteLine("open() error: " + ex.Message);

When you don’t need serial port anymore, it’s a best practice to call close() method to ask operating system to clear receive and transmit buffers and to set serial port as free:


At the end of this part 2, let’s introduce the Write() method; you can use it to send chars/bytes/strings to serial port. For example, we can send the famous “Hello World” string:

serialPort.Write("Hello World!");

A very useful tool to check if your programs are working is Portmon from SysInternals, which can monitor data flow and properties of a serial port.

Started the program, choose Computer – Connect Local; next choose the correct serial port from Capture menu and, in the same menu, flag Capture Events.

If you run the example provided, Portmon will visualize each operation (port opening, configuring, string being sent and port closing):





Leave A Response »

This website uses cookies to ensure you get the best experience on our website maggiori informazioni

Questo sito utilizza i cookie per fonire la migliore esperienza di navigazione possibile. Continuando a utilizzare questo sito senza modificare le impostazioni dei cookie o clicchi su "Accetta" permetti al loro utilizzo.