Serial Communication Using C# and Whidbey - CodeProject®
Serial Communication Using C# and Whidbey - CodeProject®
http://www.codeproject.com/KB/cs/serialcommunication.aspx
Not quite what you are looking for? You may want to try: Object Serialization using C# A Fast Serialization Technique
8,423,355 members and growing! Email Password Sign in Join
Home
Articles
Quick Answers
Discussions
Learning Zones
Features
Help!
The Lounge
serial programming in c#
Languages C# General
See Also
More like this More by this author
In this article, I will give you an introduction on how to do serial port communication on .NET platform using C#.
Article Browse Code Stats Revisions
4.13 (100 votes) 256
Sponsored Links
MX-Frame Business Application Framework www.mxframe.net Search for ASP.NET Add search engine functionality to your ASP.NET web site. Features... keyoti.com
Introduction
In this article, I will give you an introduction on how to do serial port communication on .NET platform using C#. The .NET framework version 2.0 (beta) provides features for serial communication. The framework provides System.IO.Ports namespace. The new framework provides classes with the ability to access the serial ports on a computer, and to communicate with serial I/O devices. We will be using RS 232 C standard for communication between PCs. In full duplex mode, here I am not going to use any handshaking or flow control, I will use null modem connection for communication.
The Namespace
The System.IO.Ports namespace contains classes for controlling serial ports. The most important class is the SerialPort class.
ReadLine(): Reads up to the NewLine value in the input buffer. If a New Line is not found before timeout, this method returns a null value. WriteLine(string): Writes the specified string and the New Line value to the output buffer. The
written output includes the New Line string. Open(): Opens a new serial port connection.
See Also...
In all, there are seven public constructors for creating SerialPort. But I am using the parameter less constructor, the constructor uses default property values. For example, the value of DataBits defaults to 8, and StopBits defaults to 1. The default communication port will be COM1. The public properties of SerialPort class that we will use are:
1 of 7
1/20/2012 12:55 PM
http://www.codeproject.com/KB/cs/serialcommunication.aspx
BaudRate: Gets or sets the serial baud rate. StopBits: Gets or sets the standard number of stopbits per byte. ReadTimeout: Gets or sets the number of milliseconds before a timeout occurs when a read
operation does not finish. There are many public properties, but except these three, all properties will have default values.
Creating animations with Dundas Chart for ASP.NET Smarter Data Labels with Dundas Chart SmartLabels Understanding Chart Areas with Dundas Chart for .NET Making Sense of Geographic Data with Dundas Map and AJAX DestroyWindow in VBScript SmartLink Create data-driven applications with the Hera Application Framework Towards the self-documenting database: extended properties Digital Signatures and PDF Documents WMP Power Hour APP Merge Landscape and Portrait PDFs using ASP.NET Using Barcodes in Documents Best Practices How to Retrieve EMC Centera Cluster/Pool Capabilities Using multiple keyboards with different layouts on the same machine "Hey! Is That My Car? How to Sharpen a QuickBird Satellite Image Using DotImage" Integrate your SharePoint environment into the open standards-based WebSphere Portal platform using the Visual Studio IDE
Data Transfer
In serial communication, a byte of data is transferred through a single wire one bit at a time. The packets contain a start bit, data, and stop bit. Once the start bit has been sent, the transmitter sends the actual data bits. There may either be 5, 6, 7, or 8 data bits, depending on the number you have selected. Both receiver and the transmitter must agree on the number of data bits, as well as the baud rate.
Null Modem
A Null Modem cable simply crosses the receive and transmit lines so that transmit on one end is connected to receive on the other end and vice versa. In addition to transmit and receive, DTR & DSR, as well as RTS & CTS are also crossed in a Null Modem connection. Here is the pin diagram:
As we are not using any handshake, we will use three wire connections in which we will connect pin 2 of one connector to pin 3 of the other. For both the connectors, connect pin 5 (ground) of both the connectors with each other (common ground). If you want, you can use only one PC as both transmitter and receiver for this communication. Then, just take a DB 9 connector and a small wire, and connect pin no 2 and 3 using the wire that will connect a loop back. That is, whatever you will send, the same data you will be receiving.
2 of 7
1/20/2012 12:55 PM
http://www.codeproject.com/KB/cs/serialcommunication.aspx
Here, if you want to work with default values for the public properties, then press Save Status. If you want to change the value for specified properties, then press Property. Then the following dialog will pop:
Here, you can select values for baud rate and stop bit. To save these changes, press OK. If you directly press save status or save the changed values for properties, the following form will be displayed:
Which will display the values for some of the properties. For starting communication, press Start Comm. As soon as you press the button, the following form will be displayed:
3 of 7
1/20/2012 12:55 PM
http://www.codeproject.com/KB/cs/serialcommunication.aspx
Type data in textbox which is to be transferred, followed by a new line, and press Send button. As soon as you press the button, the data will be send to the send buffer and later to the COM port. For reading the data form COM port, press Read button. If there is any data in read buffer, it will be displayed in the textbox. If there no data to be read for 500 ms, then an error message will be displayed informing the same. Here is a code example for the above application: Code for the Main app
Collapse | Copy Code
4 of 7
1/20/2012 12:55 PM
http://www.codeproject.com/KB/cs/serialcommunication.aspx
#region Using directives using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Windows.Forms; System.IO.Ports;
#endregion namespace Serialexpample { partial class Form1 : Form { //create instance of property page //property page is used to set values for stop bits and //baud rate
PropertyPage pp = new PropertyPage(); //create an Serial Port object SerialPort sp = new SerialPort(); public Form1() { InitializeComponent(); } private void propertyButton_Click(object sender, EventArgs e) { //show property dialog pp.ShowDialog(); propertyButton.Hide(); } private void sendButton_Click(object sender, EventArgs e) { try { //write line to serial port sp.WriteLine(textBox.Text); //clear the text box textBox.Text = ""; } catch (System.Exception ex) { baudRatelLabel.Text = ex.Message; } } private void ReadButton_Click(object sender, EventArgs e) { try { //clear the text box textBox.Text = ""; //read serial port and displayed the data in text box textBox.Text = sp.ReadLine(); } catch(System.Exception ex) { baudRatelLabel.Text = ex.Message; } } private void Form1_Load(object sender, EventArgs e) { } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { MessageBox.Show("Do u want to Close the App"); sp.Close(); } private void startCommButton_Click(object sender, EventArgs e) { startCommButton.Hide(); sendButton.Show(); readButton.Show(); textBox.Show();
5 of 7
1/20/2012 12:55 PM
http://www.codeproject.com/KB/cs/serialcommunication.aspx
#region Using directives using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;
#endregion namespace Serialexpample { partial class PropertyPage : Form { //variables for storing values of baud rate and stop bits private string baudR=""; private string stopB=""; //property for setting and getting baud rate and stop bits public string bRate { get { return baudR; } set { baudR = value; } } public string sBits { get { return stopB; } set { stopB = value; } } public PropertyPage() { InitializeComponent(); } private void cancelButton_Click(object sender, EventArgs e) { this.bRate = ""; this.sBits = ""; //close form this.Close(); } private void okButton_Click_1(object sender, EventArgs e) { //here we set the value for stop bits and baud rate. this.bRate = BaudRateComboBox.Text; this.sBits = stopBitComboBox.Text; // this.Close(); } } }
Note:
Both receiver and the transmitter must agree on the number of data bits, as well as the baud rate. All the connection for the DB 9 connector should be done accordingly. The article is based on pre-released documentation (.NET Framework 2.0 Beta) and is subject to change in future release.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
6 of 7
1/20/2012 12:55 PM
http://www.codeproject.com/KB/cs/serialcommunication.aspx
Article Top
Sign Up to vote
Poor
Excellent
Vote
Search Layout
Normal
Per page
25
Update
First Prev Next 19:06 8 Nov '11 17:37 9 Nov '11 22:59 30 Oct '11 19:55 31 Oct '11 2:13 13 Jun '11 1:50 15 Feb '11 20:58 7 Jan '11 2:59 21 Oct '10 0:28 13 Oct '10 6:23 11 Oct '10 21:48 9 Jul '10 14:31 2 Apr '10 22:02 14 Dec '09 6:28 26 Oct '09 11:18 4 Sep '09 22:51 7 Sep '09 9:26 9 Apr '10 2:27 25 Jun '09 2:55 25 Jun '09 7:12 25 Jun '09 20:18 25 Jun '09 10:15 29 Jun '09 1:10 20 Apr '10 19:54 21 Jun '09 6:09 20 Jun '09 1 2 3 4 5 6 7 8 9 10 11 Next Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Permalink | Advertise | Privacy | Mobile Web01 | 2.5.120109.1 | Last Updated 20 Oct 2004 Layout: fixed | fluid Article Copyright 2004 by Tapan Dantre Everything else Copyright CodeProject, 1999-2012 Terms of Use
7 of 7
1/20/2012 12:55 PM