Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Threading » Communicating with Serial Port in C#

Communicating with Serial Port in C#

This article shows how to communicated with Serial Port using C#.

Author Rank:
Technologies: .NET 2.0,Visual C# .NET
Total downloads : 1417
Total page views :  28806
Rating :
 3/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SerialPortCommunication.zip
 
ArticleAd
Become a Sponsor




This article will demonstrate how to write and receive data from a device connected to a serial port in C# and .NET. We will be writing the received data to a TextBox on a form, so this will also deal with threading.

In the past, to communicate with a Serial Port using .Net 1.1, you had to either use the Windows API, or use a third-party control. With .Net 2.0, Microsoft added this support with the inclusion of the SerialPort class as part of the System.IO.Ports namespace. Implementation of the SerialPort class is very straight-forward. To create an instance of the SerialPort class, you simply pass the SerialPort options to the constructor of the class:

// all of the options for a serial device

    // ---- can be sent through the constructor of the SerialPort class

    // ---- PortName = "COM1", Baud Rate = 19200, Parity = None,

    // ---- Data Bits = 8, Stop Bits = One, Handshake = None

    SerialPort _serialPort = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);

    _serialPort.Handshake = Handshake.None;

 

To receive data, we will need to create an EventHandler for the "SerialDataReceivedEventHandler":

// "sp_DataReceived" is a custom method that I have created

    _serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

You can also set other options, such as the ReadTimeout and WriteTimeout:

// milliseconds _serialPort.ReadTimeout = 500;

_serialPort.WriteTimeout = 500;

Once you are ready to use the Serial Port, you will need to open it: 

// Opens serial port
_serialPort.Open(); 

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.

// delegate is used to write to a UI control from a non-UI thread

private delegate void SetTextDeleg(string text);

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

void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)

{

    Thread.Sleep(500);

    string data = _serialPort.ReadLine();

    // Invokes the delegate on the UI thread, and sends the data that was received to the invoked method.

    // ---- The "si_DataReceived" method will be executed on the UI thread which allows populating of the textbox.

    this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });

}

Now we create our "si_DataReceived" method:

private void si_DataReceived(string data) { textBox1.Text = data.Trim(); }

We can now receive data from a serial port device and display it on a form. Some devices will send data without being prompted. However, some devices need to be send certain commands, and it will reply with the data that the command calls for. For these devices, you will write data to the serial port, and use the previous code to get the data that will be sent back. In my example, I will be communicating with a scale. For this particular scale, sending the command "SI\r\n" will force it to return the weight of whatever is on the scale. This command is specific for this scale. You will need to read the documentation of your serial device to find commands that it will receive. To write to the serial port, I have created a "Start" button on the form. I have added code to it's Click_Event:

private void btnStart_Click(object sender, EventArgs e)

{

    // Makes sure serial port is open before trying to write

    try

    {

        if(!(_serialPort.IsOpen))

        _serialPort.Open();

        _serialPort.Write("SI\r\n");

    }

    catch (Exception ex)

    {

        MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");

    }

}

And that is all you need to do. I have attached the Visual Studio 2005 solution.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Ryan Alford
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SerialPortCommunication.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
usage for this article?suhail12/15/2008
Hi dude, As i dont have knowledge about usage of serial ports , can I know the scenario where to use such serial ports as you mentioned here that reading data from serial ports?
Reply | Email | Delete | Modify | 
UsagesRyan12/15/2008
This code was used to connect to a floor scale. The customer that I wrote the code for would move a pallet onto the scale, and I would send the "SI\r\n" command to the scale so that it would return the weight. I also use this code to receive data from a serial port barcode scanner(without the "Write" method). When a barcode scanner scans, it sends the data through the serial port, and my application will display the scanned information on the textbox.
Reply | Email | Delete | Modify | 
Scanning for portsDonald12/20/2008
I am new to serial port, USB & hardward type. What is the best way (code wise ) to scan for the serial ports available on a given system. Thank you
Reply | Email | Delete | Modify | 
 
 
Re: Scanning for portsJohn12/22/2008

The easy way is to use SerialPorts.GetPortNames().

If you want more a more complex answer, you'll need to define what you mean by a serial port. If you want an interactive way of discovering your machine (as opposed to programmatic), then Device Manager will show you what devices are available on the system.

John

Reply | Email | Delete | Modify | 
Help with problemMark12/30/2008

I am trying to access my compass device. It take a 0x11 single byte command.

I have modified the write portion to accomodate this:

byte[] buffer_2_send = new byte[1];

 byte data_2_send = 0x11;

buffer_2_send[0] = data_2_send;

_serialPort.Write(buffer_2_send, 0, buffer_2_send.Length);//;

 It gets to the sp_DataReceived buts then errors out at the following line: string data = _serialPort.ReadLine();

It is supposed to reply with the following data but instead errors out 3 times with: Error opening/writing to serial port :: The operation has timed out.

reply: 9 bytes

0: degree high (unsigned 16bit)

1: degree low

2: minute (unsigned 8bit)

3: temperature high (status bit + 7bit)

4: temperature low (sign bit + 7bit)

5: inclination Y (sign bit + 7bit abs)

6: inclination X (sign bit + 7bit abs)

7: status 8: checksum

Any ideas?? Mark

Reply | Email | Delete | Modify | 
 
 
Re: Help with problemRyan1/30/2009
The problem is probably that the device isn't sending a carriage return at the end of the stream. ReadLine() will read data until it gets to a carriage return. Try using ReadExisting() instead and see if that works.
Reply | Email | Delete | Modify | 
multiple devices on different portsTauseef1/5/2009
In our Web Based POS we have multiple devices on different ports. Some are attached with USB ports and some are from COM ports. How can we manage all those using C#. What I am thinking to write a C# component and install at Client PC and call methds of the component using JavaScript. Any Help will be appreciated..!!
Reply | Email | Delete | Modify | 
data received from devices tylos1/30/2009
Ryan, is there a generic command that can be used to force a device to send data back to an application like u used the "SI\r\n" to obtain info from the scale?
Reply | Email | Delete | Modify | 
 
 
Re: data received from devices Ryan1/30/2009
I don't believe so. Normally, the method of return is determined by the device's configuration. Now it may be possible to send a specific command to the device that will set it's return mode to what you want. However, you would need to consult the manual for the device to see if that option is available.
Reply | Email | Delete | Modify | 
serial comm with modemstylos1/31/2009
Thanks Ryan for your reply. I was wondering Ryan, can u help me with commands that can enable me communicate with modems connected to a landline and a pc?. Actually, what i want to do is develop an application, that can detect when calls are made and record it and also be able to note the time spent in making that call and also to record missed calls and others. I would really appreciate any help given me. Thanks in advance.
Reply | Email | Delete | Modify | 
com port in c#MRK1/31/2009
thaks alot
Reply | Email | Delete | Modify | 
Auto detecting device connected to a portJason2/7/2009
I have a glucose device that I am using to get readings from. I have been looking online for weeks now for a way to check what device is connected to which port. I was sending commands to every port until I could read from the port. I figured this was bad to send commands to ports like this because of it being unsafe. Is their no way of checking what device is connected to which port? I don't no much about usb but I think devices have some way of telling the OS what it is so that the drivers can be loaded, correct? If so is there a way of checking in C# what port my device is on.
Reply | Email | Delete | Modify | 
Serial Port writing Hex value errorNaveen4/9/2009
Hi All, IM trying to write Hex value to serial port to which microcontroller is connected. It is written in C# (windows application). When i click on "Send" button Hex values has to written to Serial Port, but i need to click on "Send" button 4 - 5 times to see the output on the Oscilloscope(testing purpose) and the values i get are also incorrect. If i send out 45 bytes of data, it read 67 byte. Hex values which im sending to microcontroller are
4E
EF
2B
A1
3F
2E
B2
AF
25
C7
5C
00
00
00
00
00
00
DB
Im using the following method to write data to serial port. Here im reading data from a text file using streamreader and looping in through and writing the data.

while ((_strValue = _readfile.ReadLine()) != null)

      _SerialPort.Write(_strValue);
}
 im trying to write the first Hex value which is "4E" as string. Is this correct?
Reply | Email | Delete | Modify | 
SerialPort In C#Tien5/2/2009
Thank you very much!
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved