Serial Communication Using C #

Source: Internet
Author: User
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 providesSystem.IO.PortsNamespace. 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

TheSystem.IO.PortsNamespace contains classes for controlling serial ports. The most important class isSerialPortClass.

The SerialPort class

SerialPortClass provides a framework for Synchronous and event-driven I/O, access to pin and break states, and access to serial driver properties. it can be used to wrap stream objects, allowing the serial port to be accessed by classes that use streams. that is,SerialPortClass represents a serial port resource.

Creating SerialPort object

By creating an object of this type, we will be able to programmatically control all aspects of serial communication.

The methodsSerialPortClass that we will use are:

  • ReadLine(): Reads up to the newline value in the input buffer. If a new line is not found before timeout, this method returnsnullValue.
  • WriteLine(string): Writes the specified string and the new line value to the output buffer. The written output parameters des the new line string.
  • Open(): Opens a new serial port connection.
  • Close(): Closes the port connection.

To createSerialPortObject, all we need to do is:

<span class="cs-comment">//create a Serial Port object</span>SerialPort sp = <span class="cs-keyword">new</span> SerialPort ();

In all, there are seven public constructors for creatingSerialPort. But I am using the parameter less constructor, the constructor uses default property values. For example, the valueDataBitsUlts to 8, andStopBitsDefaults to 1. The default communication port will be com1.

The public propertiesSerialPortClass that we will use are:

  • 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 using public properties, but cannot t these three, all properties will have default values.

About Serial Port (hardware)

The serial port on your PC is a full-duplex device meaning that it can send and receive data at the same time. in order to be able to do this, it uses separate lines for transmitting and processing data. some types of serial devices support only one-way communication, and therefore, use only two wires in the cable-the transmit line and the signal ground.

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 runner 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 digoal:

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 ER 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 processing ing.

The example application

The main form:

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:

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 sent 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
<span class="cs-preprocessor">#region Using directives</span> <span class="cs-keyword">using</span> System;<span class="cs-keyword">using</span> System.Collections.Generic;<span class="cs-keyword">using</span> System.ComponentModel;<span class="cs-keyword">using</span> System.Data;<span class="cs-keyword">using</span> System.Drawing;<span class="cs-keyword">using</span> System.Windows.Forms;<span class="cs-keyword">using</span> System.IO.Ports; <span class="cs-preprocessor">#endregion</span> <span class="cs-keyword">namespace</span> Serialexpample{    partial <span class="cs-keyword">class</span> <strong>Form1</strong> : <strong>Form</strong>    {        <span class="cs-comment">//create instance of property page</span>        <span class="cs-comment">//property page is used to set values for stop bits and </span>        <span class="cs-comment">//baud rate</span>         <strong>PropertyPage</strong> pp = <span class="cs-keyword">new</span> <strong>PropertyPage</strong>();         <span class="cs-comment">//create an Serial Port object</span>        <strong>SerialPort</strong> sp = <span class="cs-keyword">new</span> <strong>SerialPort</strong>();         <span class="cs-keyword">public</span> <strong>Form1</strong>()        {            InitializeComponent();        }         <span class="cs-keyword">private</span> <span class="cs-keyword">void</span> propertyButton_Click(<span class="cs-keyword">object</span> sender, <strong>EventArgs</strong> e)        {            <span class="cs-comment">//show property dialog</span>            pp.ShowDialog();             propertyButton.Hide();        }         <span class="cs-keyword">private</span> <span class="cs-keyword">void</span> sendButton_Click(<span class="cs-keyword">object</span> sender, <strong>EventArgs</strong> e)        {            <span class="cs-keyword">try</span>            {                <span class="cs-comment">//write line to serial port</span>                sp.WriteLine(textBox.Text);                <span class="cs-comment">//clear the text box</span>                textBox.Text = <span class="cpp-string">""</span>;            }            <span class="cs-keyword">catch</span> (System.<strong>Exception</strong> ex)            {                baudRatelLabel.Text = ex.Message;            }         }         <span class="cs-keyword">private</span> <span class="cs-keyword">void</span> ReadButton_Click(<span class="cs-keyword">object</span> sender, <strong>EventArgs</strong> e)        {            <span class="cs-keyword">try</span>            {                <span class="cs-comment">//clear the text box</span>                textBox.Text = <span class="cpp-string">""</span>;                <span class="cs-comment">//read serial port and displayed the data in text box</span>                textBox.Text = sp.ReadLine();            }            <span class="cs-keyword">catch</span>(System.<strong>Exception</strong> ex)            {                baudRatelLabel.Text = ex.Message;            }        }         <span class="cs-keyword">private</span> <span class="cs-keyword">void</span> Form1_Load(<span class="cs-keyword">object</span> sender, <strong>EventArgs</strong> e)        {         }         <span class="cs-keyword">private</span> <span class="cs-keyword">void</span> Form1_FormClosing(<span class="cs-keyword">object</span> sender, <strong>FormClosingEventArgs</strong> e)        {            <strong>MessageBox</strong>.Show(<span class="cpp-string">"Do u want to Close the App"</span>);            sp.Close();        }         <span class="cs-keyword">private</span> <span class="cs-keyword">void</span> startCommButton_Click(<span class="cs-keyword">object</span> sender, <strong>EventArgs</strong> e)        {            startCommButton.Hide();            sendButton.Show();            readButton.Show();            textBox.Show();        }         <span class="cs-comment">//when we want to save the status(value)</span>        <span class="cs-keyword">private</span> <span class="cs-keyword">void</span> saveStatusButton_Click_1(<span class="cs-keyword">object</span> sender, <strong>EventArgs</strong> e)        {            <span class="cs-comment">//display values</span>            <span class="cs-comment">//if no property is set the default values</span>            <span class="cs-keyword">if</span> (pp.bRate == <span class="cpp-string">""</span> &amp;&amp; pp.sBits == <span class="cpp-string">""</span>)            {                dataBitLabel.Text = <span class="cpp-string">"BaudRate = "</span> + sp.BaudRate.ToString();                readTimeOutLabel.Text = <span class="cpp-string">"StopBits = "</span> + sp.StopBits.ToString();            }            <span class="cs-keyword">else</span>            {                dataBitLabel.Text = <span class="cpp-string">"BaudRate = "</span> + pp.bRate;                readTimeOutLabel.Text = <span class="cpp-string">"StopBits = "</span> + pp.sBits;            }             parityLabel.Text = <span class="cpp-string">"DataBits = "</span> + sp.DataBits.ToString();            stopBitLabel.Text = <span class="cpp-string">"Parity = "</span> + sp.Parity.ToString();            readTimeOutLabel.Text = <span class="cpp-string">"ReadTimeout = "</span> +                       sp.ReadTimeout.ToString();             <span class="cs-keyword">if</span> (propertyButton.Visible == <span class="cs-keyword">true</span>)                propertyButton.Hide();            saveStatusButton.Hide();            startCommButton.Show();             <span class="cs-keyword">try</span>            {                <span class="cs-comment">//open serial port</span>                sp.Open();                <span class="cs-comment">//set read time out to 500 ms</span>                sp.ReadTimeout = <span class="cs-literal">500</span>;            }            <span class="cs-keyword">catch</span> (System.<strong>Exception</strong> ex)            {                baudRatelLabel.Text = ex.Message;            }        }    }}
Code for Property dialog
<span class="cs-preprocessor">#region Using directives</span> <span class="cs-keyword">using</span> System;<span class="cs-keyword">using</span> System.Collections.Generic;<span class="cs-keyword">using</span> System.ComponentModel;<span class="cs-keyword">using</span> System.Data;<span class="cs-keyword">using</span> System.Drawing;<span class="cs-keyword">using</span> System.Text;<span class="cs-keyword">using</span> System.Windows.Forms; <span class="cs-preprocessor">#endregion</span> <span class="cs-keyword">namespace</span> Serialexpample{    partial <span class="cs-keyword">class</span> <strong>PropertyPage</strong> : <strong>Form</strong>    {        <span class="cs-comment">//variables for storing values of baud rate and stop bits</span>        <span class="cs-keyword">private</span> <span class="cs-keyword">string</span> baudR=<span class="cpp-string">""</span>;        <span class="cs-keyword">private</span> <span class="cs-keyword">string</span> stopB=<span class="cpp-string">""</span>;         <span class="cs-comment">//property for setting and getting baud rate and stop bits</span>        <span class="cs-keyword">public</span> <span class="cs-keyword">string</span> bRate        {            <span class="cs-keyword">get</span>            {                <span class="cs-keyword">return</span> baudR;            }            <span class="cs-keyword">set</span>            {                baudR = value;            }        }         <span class="cs-keyword">public</span> <span class="cs-keyword">string</span> sBits        {            <span class="cs-keyword">get</span>            {                <span class="cs-keyword">return</span> stopB;            }            <span class="cs-keyword">set</span>            {                stopB = value;            }        }         <span class="cs-keyword">public</span> <strong>PropertyPage</strong>()        {            InitializeComponent();        }         <span class="cs-keyword">private</span> <span class="cs-keyword">void</span> cancelButton_Click(<span class="cs-keyword">object</span> sender, <strong>EventArgs</strong> e)        {            <span class="cs-keyword">this</span>.bRate = <span class="cpp-string">""</span>;            <span class="cs-keyword">this</span>.sBits = <span class="cpp-string">""</span>;            <span class="cs-comment">//close form</span>            <span class="cs-keyword">this</span>.Close();        }         <span class="cs-keyword">private</span> <span class="cs-keyword">void</span> okButton_Click_1(<span class="cs-keyword">object</span> sender, <strong>EventArgs</strong> e)        {            <span class="cs-comment">//here we set the value for stop bits and baud rate.</span>            <span class="cs-keyword">this</span>.bRate = BaudRateComboBox.Text;            <span class="cs-keyword">this</span>.sBits = stopBitComboBox.Text;            <span class="cs-comment">//</span>            <span class="cs-keyword">this</span>.Close();         }    }}
Note:
  • Both runner 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 shoshould be done accordingly.
  • The article is based on pre-released documentation (. NET Framework 2.0 Beta) and is subject to change in future release.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.