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:
- GitHub repository, with all the examples related to this tutorial
- Forum
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
P.S. arrivo anche io da Dangerous Prototype 🙂
grazie per la segnalazione!
this is a nice turorial.do you have tutorial in TCP port communication in Visual basic?