Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

FREE 12 month online training for ASP.NET & MS Expression Studio and a Free copy of MS Expression Web with Windows Server Purchase
Open and read COM port data using System.IO.Ports in C# and VB .NET 2.0

Author: Zunnair
Download Source Code : 727_ComPortAPP.zip

In this simple article you will learn that how you can Open and read COM port data using System.IO.Ports Namespace.

Simply just create New Project of windows application in C#.

 

Import ServiceProcess APIs

 

C#

 

using System.IO.Ports

VB

 Imports System.IO.Ports

Drag 14 labels, one button and 5 combo boxes on the form.

 

Write Parsing functions which parse port data according to attached device

 

C#

 

public string paringdata(string data)

        {

            string[] temp = data.Split(',');

            label2.Invoke(new EventHandler(delegate { label2.Text =""; }));

 

            if (temp.Length == 4)

            {

                lblStatus.Invoke(new EventHandler(delegate { lblStatus.Text = temp[0].ToString(); }));

                lblType.Invoke(new EventHandler(delegate { lblType.Text = temp[1].ToString(); }));

                lblWeight.Invoke(new EventHandler(delegate { lblWeight.Text = temp[2].ToString(); }));

                lblUnit.Invoke(new EventHandler(delegate { lblUnit.Text = temp[3].ToString(); }));

            }

           

            return "";

           

        }

 

VB

 

Public Function paringdata(ByVal data As String) As String

        Dim temp As String() = data.Split(","c)

        label2.Invoke(New EventHandler(AddressOf ConvertedAnonymousMethod1))

 

        If temp.Length = 4 Then

            lblStatus.Invoke(New EventHandler(AddressOf ConvertedAnonymousMethod1))

            lblType.Invoke(New EventHandler(AddressOf ConvertedAnonymousMethod1))

            lblWeight.Invoke(New EventHandler(AddressOf ConvertedAnonymousMethod1))

            lblUnit.Invoke(New EventHandler(AddressOf ConvertedAnonymousMethod1))

        End If

 

        Return ""

 

    End Function

Now write following code on form Load, Port data received, and button click event

C#

private void Form1_Load(object sender, EventArgs e)

        {

            this.Text = "DevAsp Com Port APP";

            cmbBaudRate.SelectedIndex = 0;

            cmbDataBits.SelectedIndex = 0;

            cmbParity.SelectedIndex = 0;

            cmbPortName.SelectedIndex = 0;

            cmbStopBits.SelectedIndex = 0;

        }

 

        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)

        {

            // This method will be called when there is data waiting in the port's buffer

 

            // Determain which mode (string or binary) the user is in

            // Read all the data waiting in the buffer

            try

            {

                string data = "";

                data = comport.ReadLine();//.ReadExisting();

                // Display the text to the user in the terminal

                paringdata(data);

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

            //label2.Invoke(new EventHandler(delegate{label2.Text  = data;}));

 

            //Log(LogMsgType.Incoming, data);

 

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)

        {

            try

            {

                //comport.DiscardOutBuffer();

                //comport.DiscardInBuffer();

                //comport.Dispose();

                if (comport.IsOpen)

                {

                    comport.ReadExisting();

                    comport.Close();

                }

            }

            catch(Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

        private void button1_Click(object sender, EventArgs e)

        {

            // If the port is open, close it.

            try

            {

 

                if (button1.Text == "Start")

                {

                    if (comport.IsOpen) comport.Close();

                    else

                    {

                        // Set the port's settings

                        comport.BaudRate = int.Parse(cmbBaudRate.Text);

                        comport.DataBits = int.Parse(cmbDataBits.Text);

                        comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);

                        comport.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);

                        comport.PortName = cmbPortName.Text;

                        comport.ReadTimeout = 100;

                        comport.Open();

                        button1.Text = "Stop";

                    }

                }

                else

                {

                    if (comport.IsOpen)

                    {

                        comport.ReadExisting();

                        comport.Close();

                    }

                    button1.Text = "Start";

 

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

 

        }

 

 

VB

 

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)

        Me.Text = "DevAsp Com Port APP"

        cmbBaudRate.SelectedIndex = 0

        cmbDataBits.SelectedIndex = 0

        cmbParity.SelectedIndex = 0

        cmbPortName.SelectedIndex = 0

        cmbStopBits.SelectedIndex = 0

    End Sub

 

    Private Sub port_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)

        ' This method will be called when there is data waiting in the port's buffer

 

        ' Determain which mode (string or binary) the user is in

        ' Read all the data waiting in the buffer

        Try

            Dim data As String = ""

            data = comport.ReadLine()

            '.ReadExisting();

            ' Display the text to the user in the terminal

            paringdata(data)

        Catch ex As Exception

            MessageBox.Show(ex.Message)

        End Try

        'label2.Invoke(new EventHandler(delegate{label2.Text = data;}));

 

        'Log(LogMsgType.Incoming, data);

 

    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)

        Try

            'comport.DiscardOutBuffer();

            'comport.DiscardInBuffer();

            'comport.Dispose();

            If comport.IsOpen Then

                comport.ReadExisting()

                comport.Close()

            End If

        Catch ex As Exception

            MessageBox.Show(ex.Message)

        End Try

    End Sub

    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)

        ' If the port is open, close it.

        Try

 

            If button1.Text = "Start" Then

                If comport.IsOpen Then

                    comport.Close()

                Else

                    ' Set the port's settings

                    comport.BaudRate = Integer.Parse(cmbBaudRate.Text)

                    comport.DataBits = Integer.Parse(cmbDataBits.Text)

                    comport.StopBits = DirectCast([Enum].Parse(GetType(StopBits), cmbStopBits.Text), StopBits)

                    comport.Parity = DirectCast([Enum].Parse(GetType(Parity), cmbParity.Text), Parity)

                    comport.PortName = cmbPortName.Text

                    comport.ReadTimeout = 100

                    comport.Open()

                    button1.Text = "Stop"

                End If

            Else

                If comport.IsOpen Then

                    comport.ReadExisting()

                    comport.Close()

                End If

 

                button1.Text = "Start"

            End If

        Catch ex As Exception

            MessageBox.Show(ex.Message)

        End Try

 

    End Sub

 

 

This is simple code to open port and Read data from port. Here comport.Open(); method is use to open port and comport.ReadLine() and comport.ReadExisting() methods are use to Read data from port.

 

Article Comments
good work

Posted on 8/12/2008 3:28:54 AM by peter

I am trying to connect and read data from Lab test machines, i got a success, for almost all of the machines but with Vitros ECI, I can read data in Hyper Terminal but program is unable to receive any data, Vitros ECI reacts like there is no Lab Computer connected.

Any Ideas why?

Posted on 11/8/2009 10:10:07 AM by Asad

I'm kalpa iwill try "port in c#" thank

Posted on 7/28/2010 2:53:01 AM by Kalpa Isuru Kumara

this is great i have been searching for years looking for such guide like this thanks ! god bless

Posted on 11/5/2010 8:47:21 PM by Kim

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< Count total number of page in PDF file in C# .NET 2.0?

Disclaimer - Privacy
© 2002-2014 DevASP.net