Escolar Documentos
Profissional Documentos
Cultura Documentos
Summary
1. How to use C Sharp to manage a windows COM port.
2. How to obtain a list of available COM ports.
This article comes with a sample application written in C# with source code included.
Download from: http://www.kicchip.co.uk/download/articles/serial_c_sharp.zip
In order to open the serial port, the user must first set the PortName , BaudRate, Handshake and
StopBits properties.
Once the connection properties have been set, the port can be opened using the Open() routine.
/* This event fires when the user clicks the "Open" button
* It attempts to open the COM port using the user settings.
*/
private void btnOpen_Click(object sender, EventArgs e)
{
try {
serialPort1.PortName
= lbComPort.Text
serialPort1.BaudRate
= Convert.ToInt32(tbBaudRate.Text)
serialPort1.Handshake
= Handshake.None
serialPort1.StopBits
= StopBits.One
serialPort1.Open()
} catch (Exception x) {
MessageBox.Show(x.Message)
}
SetButtonActions()
}
;
;
;
;
;
;
;
Sending data..
Data is transmitted from the PC to the serial port via the Write() routine.
/* This event fires when the user clicks the "Write Byte" button
*/
private void btnWriteByte_Click(object sender, EventArgs e)
{
try
{
byte[] buf = { Convert.ToByte(tbWriteString.Text) } ;
serialPort1.Write(buf , 0, 1 )
;
}catch (Exception x) {
MessageBox.Show(x.Message)
;
}
}
Reading data..
Data is read from the serial port using the ReadByte() routine.
/* This event fires when the user clicks the "Read Data" button
*/
private void btnReadData_Click(object sender, EventArgs e)
{
try {
// if we have data to read
if ( serialPort1.BytesToRead > 0) {
/* User can select between seeing the ascii char of the data
* or its numeric value
*/
if (cbDisplayAsASCII.Checked) {
// append data as ASCII char
tdDataWindow.Text = Convert.ToString(
Convert.ToChar(
serialPort1.ReadByte()
)
) ;
} else {
// append data as its number value
tdDataWindow.Text = Convert.ToString(
serialPort1.ReadByte()
) ;
}
}
} catch (Exception x) {
MessageBox.Show(x.Message)
;
}
}
It is imperative to close the connection when finished using the port. This is done using the Close()
routine.
/* This event fires when the user clicks the "Close" button
* It attempts to close the COM port
*/
private void btnClose_Click_1(object sender, EventArgs e)
{
try {
serialPort1.Close() ;
} catch (Exception x) {
MessageBox.Show(x.Message)
;
}
SetButtonActions() ;
}
System.IO.Ports
; // Port