Serial port communication in c# – part 1

luca 25/10/2011 5

If you work on electronic projects, you often need to make them talk with a personal computer: the easiest way to do that is use a serial port (real or emulated by one of those USB->serial adapter you can find in stores or embedded in prototyping platform like Arduino).

This tutorial will show you how to write, in c#, programs which are able to communicate with our project via serial port.

The objects we’re going to use are present in a particular namespace, so you need to include it in your program:

using System.IO.Ports;

Usually the first thing your program should do at the beginning is to detect how many serial ports are present in your personal computer and retrieve their names. You can use the static method GetPortNames() of the object SerialPort. Indeed, with the following line of code:

string[] serialPorts = SerialPort.GetPortNames();

the string array serialPorts will contain the names of the available serial ports.

You may print in console the names with a simple loop on the array:

foreach (string serialPort in serialPorts)

Or, if our program has a GUI, fill a ComboBox:

foreach (string comPort in comPorts)
if(comPorts.Length > 0)
    cbSerialPort.SelectedIndex = 0;

if(comPorts.Length > 0)
cbSerialPort.SelectedIndex = 0;

(third and forth line will select – if at least one is present – the first available serial port).

I wrote two programs  (a console and a GUI one) as examples:



  1. Enea 12/11/2011 at 18:49 - Reply

    grazie di aver condiviso questa utile risorsa sulla comunicazione seriale.
    Ti segnalo anche

    estratto dalla versione inglese, con codice sogente

  2. Enea 12/11/2011 at 18:49 - Reply

    P.S. arrivo anche io da Dangerous Prototype :)

  3. luca 12/11/2011 at 18:56 - Reply

    grazie per la segnalazione!

  4. Daj 28/11/2012 at 04:48 - Reply

    this is a nice you have tutorial in TCP port communication in Visual basic?

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.