Serial port communication in c# – part 1

by luca
5 comments

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)
    Console.WriteLine(serialPort);

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

foreach (string comPort in comPorts)
    cbSerialPort.Items.Add(comPort);
 
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:


Resources:

Related Posts

5 comments

Comunicazione seriale in c# – seconda parte Saturday October 29th, 2011 - 10:36 AM

[…] aver visto come elencare le porte seriali presenti nel nostro PC, in questa seconda parte iniziamo ad […]

Reply
Enea Saturday November 12th, 2011 - 06:49 PM

Ciao,
grazie di aver condiviso questa utile risorsa sulla comunicazione seriale.
Ti segnalo anche
http://it.emcelettronica.com/comunicazione-seriale-c

estratto dalla versione inglese, con codice sogente

Reply
Enea Saturday November 12th, 2011 - 06:49 PM

P.S. arrivo anche io da Dangerous Prototype 🙂

Reply
luca Saturday November 12th, 2011 - 06:56 PM

grazie per la segnalazione!

Reply
Daj Wednesday November 28th, 2012 - 04:48 AM

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

Reply

Leave a Comment

13 + nineteen =