Serial Programming using C sharp on Windows
C# (C Sharp) is a general purpose, object oriented language developed by Microsoft Corporation to work with .NET Framework. C# can also work with open source implementations of .NET Frame work like Mono. C# is similar to java ,so if you are familiar with java ,it is an easy language to pick up.
You can also check out a GUI based serial port program written in C# here
In this tutorial we are going to program the serial port on a windows PC using C# and communicate with a microcontroller board. The Tutorial will also show how to set and clear the RTS and DTR pins of PC serial port.
Compilers and IDE's used
In this tutorial I am using the Microsoft Visual Studio Express Edition to compile the codes. You can also use SharpDevelop which is an open source IDE for C# and VB.NET. The IDE also has an automatic code conversion feature to convert from C# to VB.net .
If you are new to Visual Studio,you can check this short tutorial (Please note that the tutorial is written for C but most of the steps are similar, the differences are shown at the end) .
USB2SERIAL - Any easy to use multi protocol converter that can convert from USB to RS485/RS232/Serial.The Board comes with selectable voltage levels for interfacing with 5V and 3.3V logic families.
Selecting the COM port
To find out the COM number corresponding to your serial port,
Open Device Manager by right clicking on My Computer icon and selecting "Manage → Device Manager".Under Ports(COM & LPT) you can see the parallel and serial ports (COM) detected by your system.
If your PC has any hardware ports, it will be shown either as COM1 or COM2 under the Ports Section. I am using a FTDI based USB to Serial Converter (USB2SERIAL) which is recognized as COM46. If you double click on COM46,you can see the details of the corresponding port.
Serial port communication is accomplished using the SerialPort Class provided by the dotnet framework. The class is present in the System.IO.Ports namespace .In order to access the SerialPort class you have to include the System.IO.Ports namespace in your source file. In Visual studio if everything is properly configured the auto complete feature will show the namespace while typing.
When creating the project for Serial Communication ,it is recommended to create a Windows Console Application project.
Writing into Serial Port
Now lets write a small program that will open a connection to serial port and configure BaudRate,Stop bits ,Parity etc and send a character to Microcontroller board connected to it.The microcontroller and PC are interfaced using null modem cable and is shown at the bottom of this page.
using System.IO.Ports; //namespace containing SerialPort Class
MyCOMPort.Open(); // Open the port
After you have typed/copied the code into the Visual Studio IDE.Compile and Run it by pressing F5.the code will open a connection to the serial port ("COM46") ,write an ASCII " A " character and close the port.If you are using the USB2SERIAL converter brought from this site, TX_RX_LED (D1) will blink signifying that a character is transmitted.
Please note that "COM46" is the serial port number assigned by my computer,the COM number will be different in your system.Please check the device manager and find out COM number assigned to your serial port or USB to serial converter.
If you have entered an invalid COM port number that do not exist in your computer (I have used COM4 to show that),Visual Studio will generate an exception.
In the above code we are creating a SerialPort object of the name MyCOMPort
SerialPort MyCOMPort = new SerialPort();
which is then use to configure the parameters and communicate with the serial port.After the SerialPort object MyCOMPort is created,We assign the name of the serial port to be opened to it.
MyCOMPort.PortName = "COM46";
Parity can be selected as Even,Odd or None using Parity.Even , Parity.Odd ,Parity.None.The good thing about the intellisense feature in Visual studio is that it will show all the available options when you type.
MyCOMPort.Parity = Parity.None;
You can see the options of Stop bits also in the same way.In the above program we are using one stop bit.
MyCOMPort.StopBits = StopBits.One;
After the settings are configured we open the serial port using MyCOMPort.Open(); and then write a character or string using MyCOMPort.Write("A");After the communication is over we close the port using MyCOMPort.Close();
Here is the screenshot of Program running on Windows 7 transmitting a ASCII character 'A' to the microcontroller.Here COM81 is the name of my COM port.
One problem with reading from Serial Port is that you need some data coming from the outside word through the serial port which you can read.One way to solve is to use another computer and connect its serial port with your's using a NULL Modem cable.Another way is to use a microcontroller board like Arduino,MSP430 Launchpad etc to transmit a string to your computers serial port.In this example i am going to use the later method,where a MSP430 Launchpad will transmit a string of characters toward my PC using its UART which is then read by C# program running on the PC.
One thing to note is that PC's may have hardware based DB9 RS232 serial ports (quite rare now a days),When you are connecting your microcontroller board with PC make sure that it(microcontroller board) has an RS232 decoder circuit (usually based on MAX232).Connecting the outputs of a DB9 serial port directly to microcontroller pins will damage it.
In this example I am using a MSP430 launchpad which is connected to a laptop using a USB to Serial Converter (USB2SERIAL).USB2SERIAL provides access to the TTL outputs of FT232 (RXD and TXD ) through berg strip connectors which can then be directly connected to the UART of MSP430.It also has selectable TTL voltage levels (3V and 5V) so that it can be directly connected to 3.3V microcontrollers like MSP430. The TXD(TTL) of MSP430 is connected to RXD (TTL) of USB2SERIAL and vice versa .Whatever the MSP430 microcontroller transmits is received by the PC through USB2SERIAL.You can use any USB to Serial converter of your choice for this.The microcontroller side code is explained here.
Here is a picture of the connection between the MSP430 and USB2SERIAL (USB to Serial/RS485 converter).
Reading from the serial port is similar to writing to serial port.Most of the code remains same ,instead of using MyCOMPort.Write() we use MyCOMPort.ReadLine().The data received in the PC serial port is read using MyCOMPort.ReadLine() and then printed on the screen.Here is the code for reading from serial port.
//COM port settings to 8N1 mode
MyCOMPort.Open(); // Open the port
MyCOMPort.Close(); // Close port
If you compile and run this program,the program will execute and wait for the string to be transmitted by the MSP430 microcontroller.
One thing to note that, is Console.ReadLine() will return only after encountering the end of line character "\n".Please make sure that the microcontroller sends the "\n" character otherwise the Console.ReadLine() will never return and program will hang.
Press the reset button on the Launchpad board so that MSP430 will transmit the string "Hello from MSP430" .When the string is received by PC ,it is displayed on the screen using Console.WriteLine().
Please note that i have modified the earlier program to be more informative by adding a few extra lines of code.In the last two examples (reading and writing to serial port code ),I have hard coded the COM port number in the program itself like this MyCOMPort.PortName = "COM46"; .In the new one,i have made the COM port selection interactive by adding the following lines
Console.Write("Enter the COM Port Number [eg COM32] ->");
COM_PortName = COM_PortName.Trim();
MyCOMPort.PortName = COM_PortName;
Console.ReadLine() function is used to read the COM port number in the format "COM32".
The extra spaces present in the input value is trimmed by using
COM_PortName = COM_PortName.Trim(); .
Then the whole string is converted to upper case by using
COM_PortName = COM_PortName.ToUpper(); .
Finally the port name is assigned to
MyCOMPort.PortName = COM_PortName;
and then the port is opened. The full code is available in the zip file.
After reading and writing to the serial port,its time to play with the other pins of a serial port like DTR and RTS .In Some USB to Serial Converters DTR and RTS pins are not available,only the RXD,TXD and Ground pins are available outside.In USB2SERIAL all 9 pins are brought outside to berg strips which you can easily access.
One use of RTS and DTR pins is used to control the RS485 chips during a USB to RS485 conversion.When you have to control some thing over several 100's of meters ,RS232 or USB will not be suitable.In such cases we have to use RS485 protocol, one problem with RS485 is that most PC's / Laptops will not have an RS485 port.You can solve that problem by using USB to RS485 converters like USB2SERIAL .In USB2SERIAL RTS pin is used to put the RS485 chip in receive mode and DTR pin is used to put theRS485 chip in transmit mode.
Please note that in FT232 based USB to Serial converters (like USB2SERIAL) the RTS and DTR pins are inverted internally so setting the pins high will make then low and vice versa
The SerialPort Class in .NET Framework have two properties called RtsEnable and DtrEnable enable to control the RTS and DTR pins respectively.The code shown below will show you how to control the pins.
MyCOMPort.PortName = "COM46"; // Assign the name of the serial port to be opened
MyCOMPort.RtsEnable = true; // RTS pin = 1 ,~RTS = 0
MyCOMPort.Close(); // Close port
}//end of Main
The RTS pin is set high using MyCOMPort.RtsEnable = true; and it is set low using MyCOMPort.RtsEnable = false; .
Since the pins are inverted internally (in FT232) setting the RTS pin MyCOMPort.RtsEnable = true; will make the pin LOW and
Clearing the pin using MyCOMPort.RtsEnable = false; will make it HIGH,same goes for DTR pin also.
Here is a picture of RTS and DTR lines of USB2SERIAL connected to LED's .
Please note that the USB2SERIAL also has onboard LED's near the RS485 section to display the status of RTS and DTR lines used to control the RS485 chip.
Screenshot of the program executing on windows
Back to Serial Programming Tutorials