SerialPort (RS-232 COM Port) in C# .NET
.NET has a great class called SerialPort (MSDNreference) part of .NET 2.0 and is freely available in C#Express on MSDN. It is easy to use.
BTW, this article is about communicating through the PC's Serial COM RS-232 port using Microsoft .NET 2.0 or later by using the System.IO.Ports.SerialPort class.
Sample Code: SerialPort
Prerequisites: You will need Microsoft .NET 3.5 to run the app. It is installed as part of the regular Windows Updates (make sure your computer is fully up to date, see MicrosoftUpdates for more info) or if that doesn’t work for some reason, you can install.NET 3.5 from here.
using System;
using System.IO.Ports;
using System.Windows.Forms;
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 to keep 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());
}
}
}
No comments:
Post a Comment