RS232 Communication in C#

In this article, I am going to describe some basics about how we can perform serial port communication from our C#.NET applications.
What is RS232?

RS-232 is a standard for serial communication transmission of data. RS232 is a specification for serial communications between a DCE (Data communication equipment) and DTE (Data terminal equipment) i.e., connection between the computer and modem.




How to get connected port names from pc?
In order to receive data from pc through serial port 1st we need to have a list of serial ports that are connected to the pc. In the below example I will demonstrate the logic to get the port name.

Steps:-

  1. Create a new windows application project
  2. Drag and drop the Combo Box on to the windows form and name it as “cmbComSelect”.
  3. Drag on the “serial port” control from the toolbox and place it on the windows form. Name the serial port as “port”
  4. System.IO.Ports Namespace is used because it contains classes for controlling serial ports

Code to get port names into ComboBox:-

1.  Create a string array method to browse all the available port names.
           string[] ports = SerialPort.GetPortNames();

2.     Now add all ports to the combo box using for each loop on page load event
             foreach (string port in ports)
       {
        cmbComSelect.Items.Add(port);
       }

3.    Now if you run your application you will get all the port names in the combo box in the     following manner.


Code to Open connection of port:-

1. Now raise a “selectionchangecommited” event of the cmbComSelect Combobox.
2.  If you click the port name the port opens if the port is not opened or else port is not            opened.

     If (port.IsOpen) port.Close();
      port.PortName = cmbComSelect.SelectedItem.ToString ();

    // try to open the selected port:
     Try
    { port. Open ();}

     // give a message, if the port is not available:
     Catch
     {
           MessageBox.Show("Serial port  cannot be opened ");
           cmbComSelect.SelectedText = "";
      }
 3.  Now we are ready once we opened the serial port communication.

Receiving Data into Textbox through Rs232:-

Now we are ready to receive data. However, to write this data to the Textbox on a form, we need to create a delegate. .Net does not allow cross-thread action, so we need to use a delegate. The delegate is used to write to the UI thread from a non-UI thread.
     
// this delegate enables asynchronous calls for setting
// the text property on a Textbox control:

   Delegate void SetTextCallback (string text);

Also declare a string as global variable i.e., string InputData = String.Empty;




We will now create the "port_DataReceived" method that will be executed when data is received through the serial port:

Private void  port_DataReceived (object sender, SerialDataReceivedEventArgs e)
{
  InputData = port.ReadExisting ();
  If (InputData != String.Empty)
  {
    SetText (InputData);
  }
}

We will now see what is the SetText method and its Code.

Private void SetText(string text)
 {
  // InvokeRequired required compares the thread ID of the
  // calling thread to the thread ID of the creating thread.
  // If these threads are different, it returns true.
  if (this.txtIn.InvokeRequired)
  {
      SetTextCallback d = new SetTextCallback(SetText);
      this.Invoke(d, new object[] { text });
  }
  else this.txtIn.Text += text;
 }




Sending Data to connected Comports using Rs232 port:-

Now we will see how to send data from textbox to the connected serial port. Raise a “btn_send” click event.

private void btnSend_Click(object sender, EventArgs e)
{
   if (port.IsOpen) port.WriteLine (txtOut.Text);
   else
MessageBox.Show("Serial port is closed!");
 txtOut.Clear();
}




THANK YOU…ENJOY CODING



Comments