SerialPort (RS-232 Serial COM Port) in C# .NET

SerialPort (RS-232 Serial COM Port) in C# .NET

Way in the Past...

Back in my early (pre C# MVP) days, I had written an article on DevHood titled Serial COM Simply in C#. It became quite popular and is (currently) the top Google search for "serial c#". Now every week I get several e-mails with people asking questions and it is high time for some serious updating.

The article was (originally) written soon after .NET was introduced to the world, and other .NET serial port controls had not yet been written. So at the time, this was an easy solution. Just use the MSComm.ocx control from VS6 which most Devs had at the time. Now however, there are many easier and preferred methods than dealing with the complexities of interoping with an old legacy (non-.NET) ActiveX OCX control.

A Bright Future is Here!

Today, the primary solution is to use the new SerialPort control that is part of .NET 2.0 (currently in Beta) and is freely available in C# Express on MSDN. It is considerably easier to use and is a true .NET component.

For loyal fans of the tutorial, I've written a sample application, SerialPort Terminal, which you can try out to see how the new SerialPort control is used. Since Visual Studio 2005 / .NET 2.0 is still under development, you will need to compile the app on your system before running it.

Continued Support

Due to the high volume of e-mail I've been receiving on serial port communication in general, I've created a SerialCom FAQ. Which for the most part says "use SerialPort in .NET 2.0".

For those of you who I've directed to this blog post, please understand that I'm just another guy working away at a full time job (helping manage the release of Team System) who has worked with serial RS-232 ports in the past (moving on to USB now). I like to help people, hence I wrote the original article, this sample code, and the FAQ, but do not have the resources to answer additional serial port communication questions. Please check out the SerialCom FAQ for other .NET COM Port solutions and technical support options.

Get Connected Up

You can obtain USB to Serial adapters (from NewEgg, search using Froogle) and have just about as many ports on your PC as you like. I carry around two adapters with a null modem (what is it?, search Froogle) between them so I can create a loopback to send & receive through to separate ports on most any computer. I'd recommend doing the same for when writing code for the serial port.

If you'd like to quickly and easily create your own external devices to communicate with the PC, I recommend starting with the Parallax BASIC Stamp modules. Specifically the BASIC Stamp 2 Module (~$50) in a Starter Kit (~$170) is a good springboard. Parallax has lots of easy accessories (such as LCDs, RF, Sounds, AD & DA, etc) for their modules. After that you could migrate to an Atmel Microcontroller (recommended) or Microchip PIC.

See project photos of the Basic Stamp microcontroller and USB to Serial w/ null modem loopback.

Time for the Code

Here is an example of how easy it is to use the new SerialPort control.

Very simply, here is how you can send a bit of data out the port.

      
      
// This is a new namespace in .NET 2.0 that contains the SerialPort class using System.IO.Ports; private static void SendSampleData() { // Instantiate the communications port with some basic settings SerialPort port = new SerialPort( " COM1 " , 9600 , Parity.None, 8 , StopBits.One); // Open the port for communications port.Open(); // Write a string port.Write( " Hello World " ); // Write a set of bytes port.Write( new byte [] { 0x0A , 0xE2 , 0xFF }, 0 , 3 ); // Close the port port.Close(); }


Now let's take a look at what it takes to read data in from the communications port. This demonstrates reading text; for an example of reading binary data, see my SerialPort Terminal sample app.

  1. Create a new "Console Application" and replace all the default class code with this code
  2. Add a reference to "System.Windows.Forms" to the project
  3. Run w/ F5, to exit the app, press Ctrl-Break.
  4. Get Connected Up with two USB to Serial adapters and a null modem
  5. Use another app, the code above, or the SerialPort Terminal example to send data and watch it come in with this code

      
      
#region Namespace Inclusions using System; using System.IO.Ports; using System.Windows.Forms; #endregion namespace SerialPortExample { class SerialPortProgram { // Create the serial port with basic settings private SerialPort port = new SerialPort( " COM1 " , 9600 , Parity.None, 8 , StopBits.One); [STAThread] static void Main( string [] args) { // Instatiate this class new SerialPortProgram(); } private SerialPortProgram() { Console.WriteLine( " Incoming Data: " ); // Attach a method to be called when there is data waiting in the port's buffer port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); // Begin communications port.Open(); // Enter an application loop which keeps this thread alive Application.Run(); } private void port_DataReceived( object sender, SerialDataReceivedEventArgs e) { // Show all the incoming data in the port's buffer Console.WriteLine(port.ReadExisting()); } } }


One of the (several) new methods that is supported, and one I'm very glad is finally here, is the ability to obtain a list of the COM ports installed on the computer (ex: COM1, COM2, COM4). This is definately helpful when you want to present the list of ports avalible for the user to select from (as in the SerialPort Terminal Win App example).

      
      
foreach ( string s in SerialPort.GetPortNames()) System.Diagnostics.Trace.WriteLine(s);


Here are two helpful little methods for sending files through the serial port. Of course, these are the bare essentials and as always, you should check to make sure the port is open first (port.IsOpen) and use try/catch around trying to open a file, but you get the gist with this code. The binary sending routine is limited to about 2GB (the size of an int), but this should be okay for most uses.

      
      
using System.IO; private static void SendTextFile(SerialPort port, string FileName) { port.Write(File.OpenText(FileName).ReadToEnd()); } private static void SendBinaryFile(SerialPort port, string FileName) { using (FileStream fs = File.OpenRead(FileName)) port.Write(( new BinaryReader(fs)).ReadBytes(( int )fs.Length), 0 , ( int )fs.Length); }


RS-232 Project Photos

Get connected up with the parts for fun projects like these.
Each of these involve RS-232 serial port communications.

Get connected up with the parts for fun projects like these.
Each of these involve RS-232 serial port communications.
Just what's needed to get started with microcontrollers,
a Basic Stamp, mini LCD display, power, and RS-232 port.

Two USB to Serial adapters with a null modem
to loopback and test your serial software.

The brains to a mini automated radio station that let me
control my PC & home using my HAM radio from around town.


Port Wiring Notes

DB9 Male (Pin Side)                   DB9 Female (Pin Side)
DB9 Female (Solder Side)              DB9 Male (Solder Side)
    -------------                          -------------
    / 1 2 3 4 5 /                          / 5 4 3 2 1 /
     / 6 7 8 9 /                            / 9 8 7 6 /
      ---------                              ---------

DB9 Female to DB9 Female Null-Modem Wiring
 2 |  3 |  7 |  8 | 6&1|  5 |  4
---- ---- ---- ---- ---- ---- ---- 
 3 |  2 |  8 |  7 |  4 |  5 | 6&1

9-pin   25-pin  Assignment                 From PC
------  ------  -------------------------  ------------
Sheild  1       Case Ground                Gnd
1       8       DCD (Data Carrier Detect)  Input
2       3       RX  (Receive Data)         Input
3       2       TX  (Transmit Data)        Output
4       20      DTR (Data Terminal Ready)  Output
5       7       GND (Signal Ground)        Gnd
6       6       DSR (Data Set Ready)       Input
7       4       RTS (Request To Send)      Output
8       5       CTS (Clear To Send)        Input
9       22      RI  (Ring Indicator)       Input

- RTS & DTR are binary outputs that can be manually set and held
- DCD, DSR, CTS, and RI are binary inputs that can be read
- RX & TX can not be set manually and are controlled by the UART
- maximum voltages are between -15 volts and +15 volts
- binary outputs are between +5 to +15 volts and -5 to -15 volts
- binary inputs are between +3 to +15 volts and -3 to -15 volts
- input voltages between -3 to +3 are undefined while output voltages
  between -5 and +5 are undefined
- positive voltages indicate ON or SPACE, negative voltages indicate
  OFF or MARK

Other Resources

Here are some additional sites, libraries, tutorials, etc. These are links that I just found around the net and am providing for convenience (they are not endorsed).

Where CF = Compact Framework

The Final Say (aka Conclusion)

The new SerialPort class in .NET 2.0 rocks! It is much easier to use than getting the old MSComm.ocx control going in a .NET app, contains new functionality, is a 'native' .NET control, has docs built into the MSDN Library, and is easy to use.

posted on Wednesday, March 23, 2005 7:28 PM

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值