SERIAL
COMMUNICATION
In telecommunication and
computer science, serial communication is the process of sending data one bit
at a time, sequentially, over a communication channel or computer bus. This is
in contrast to parallel communication, where several bits are sent as a whole,
on a link with several parallel channels.
Setting Up
Setting Up
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO.Ports
using System.Windows.Forms;
System.IO.Ports is the
class to use without resulting to low level hacking. This covers all the serial
ports that appear on the machine.
SerialPort ComPort = newSerialPort();
This will
create an object called
ComPort
. This will create a serial port object with the following
parameters as default 9600bps, no parity, one stop bit and no flow control.
Shown below is the form:
This
is standard Windows Forms Application via File menu. To this add the button
(name Ports) and a Rich Text Box.The button is called btnGetSerialPorts and
the Rich Text called as rtbIncomingData (the name will become apparent
later).The rich text box is used as it is more flexible than the ordinary text
box. Its uses for sorting and aligning text are considerably more than the
straight textbox.
This
shows all the devices that appear as com ports, a mistake to make is thinking
that a device if plugged into the USB will appear as a COM Port.
The baud rate is the amount of possible events that can happen in a second. It is displays usually as a number of bit per second, the possible number that can be used are 300, 600, 1200, 2400, 9600, 14400, 19200, 38400, 57600, and 115200 (these come from the UAR 8250 chip is used, if a 16650 the additional rates of 230400, 460800 and 921600) .
namespace CodeProjectSerialComms
{
SerialPort ComPort = newSerialPort();
internaldelegatevoidSerialDataReceivedEventHandlerDelegate(object sender, SerialDataReceivedEventArgs );
internaldelegatevoidSerialPinChangedEventHandlerDelegate(object sender, SerialPinChangedEventArgs e);
privateSerialPinChangedEventHandler SerialPinChangedEventHandler1;
delegatevoidSetTextCallback(string text);
string InputData = String.Empty;
public Form1()
{
InitializeComponent();
SerialPinChangedEventHandler1 = newSerialPinChangedEventHandler(PinChanged);
ComPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
}
privatevoid btnGetSerialPorts_Click(object sender, EventArgs e)
{
string[] ArrayComPortsNames = null;
int index = -1;
string ComPortName = null;
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
cboPorts.Items.Add(ArrayComPortsNames[index]);
}while(!((ArrayComPortsNames[index]==ComPortName)||(index == ArrayComPortsNames.GetUpperBound(0))));
Array.Sort(ArrayComPortsNames);
The baud rate is the amount of possible events that can happen in a second. It is displays usually as a number of bit per second, the possible number that can be used are 300, 600, 1200, 2400, 9600, 14400, 19200, 38400, 57600, and 115200 (these come from the UAR 8250 chip is used, if a 16650 the additional rates of 230400, 460800 and 921600) .
The
next box is the number of Data bits, these represent the total number of
transitions of the data transmission (or Tx line) 8 is the standard ( 8 is
useful for reading certain embedded application as it gives two nibbles (4 bit
sequences).
The Handshaking
property is used when a full set of connections are used (such as the grey 9
way D-types that litter my desk). It was used originally to ensure both ends
lined up with each other and the data was sent and received properly. A common
handshake was required between both sender and receiver. Below is the code for
the combo box:
Here
is the complete code for serial communication between transmitter and receiver.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
namespace CodeProjectSerialComms
{
SerialPort ComPort = newSerialPort();
internaldelegatevoidSerialDataReceivedEventHandlerDelegate(object sender, SerialDataReceivedEventArgs );
internaldelegatevoidSerialPinChangedEventHandlerDelegate(object sender, SerialPinChangedEventArgs e);
privateSerialPinChangedEventHandler SerialPinChangedEventHandler1;
delegatevoidSetTextCallback(string text);
string InputData = String.Empty;
public Form1()
{
InitializeComponent();
SerialPinChangedEventHandler1 = newSerialPinChangedEventHandler(PinChanged);
ComPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
}
privatevoid btnGetSerialPorts_Click(object sender, EventArgs e)
{
string[] ArrayComPortsNames = null;
int index = -1;
string ComPortName = null;
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
cboPorts.Items.Add(ArrayComPortsNames[index]);
}while(!((ArrayComPortsNames[index]==ComPortName)||(index == ArrayComPortsNames.GetUpperBound(0))));
Array.Sort(ArrayComPortsNames);
if (index == ArrayComPortsNames.GetUpperBound(0))
{
ComPortName = ArrayComPortsNames[0];
}
//get first item print in text
cboPorts.Text = ArrayComPortsNames[0];
//Baud Rate
cboBaudRate.Items.Add(300);
cboBaudRate.Items.Add(600);
cboBaudRate.Items.Add(1200);
cboBaudRate.Items.Add(2400);
cboBaudRate.Items.Add(9600);
cboBaudRate.Items.Add(14400);
cboBaudRate.Items.Add(19200);
cboBaudRate.Items.Add(38400);
cboBaudRate.Items.Add(57600);
cboBaudRate.Items.Add(115200);
cboBaudRate.Items.ToString();
//get first item print in text
cboBaudRate.Text =
cboBaudRate.Items[0].ToString();
//Data Bits
cboDataBits.Items.Add(7);
cboDataBits.Items.Add(8);
//get the first item print it in the text
cboDataBits.Text = cboDataBits.Items[0].ToString();
//Stop Bits
cboStopBits.Items.Add("One");
cboStopBits.Items.Add("OnePointFive");
cboStopBits.Items.Add("Two");
//get the first item print in the text
cboStopBits.Text = cboStopBits.Items[0].ToString();
//Parity
cboParity.Items.Add("None");
cboParity.Items.Add("Even");
cboParity.Items.Add("Mark");
cboParity.Items.Add("Odd");
cboParity.Items.Add("Space");
//get the first item print in the text
cboParity.Text =
cboParity.Items[0].ToString();
//Handshake
cboHandShaking.Items.Add("None");
cboHandShaking.Items.Add("XOnXOff");
cboHandShaking.Items.Add("RequestToSend");
cboHandShaking.Items.Add("RequestToSendXOnXOff");
//get the first item print it in the text
cboHandShaking.Text = cboHandShaking.Items[0].ToString();
}
privatevoid port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{
InputData = ComPort.ReadExisting();
if (InputData != String.Empty)
{
this.BeginInvoke(newSetTextCallback(SetText), newobject[] { InputData });
}
}
privatevoid SetText(string text)
{
this.rtbIncoming.Text += text;
}
privatevoid btnPortState_Click(object sender, EventArgs e)
{
if (btnPortState.Text == "Closed")
{
btnPortState.Text = "Open";
ComPort.PortName = Convert.ToString(cboPorts.Text);
ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
ComPort.DataBits = Convert.ToInt16(cboDataBits.Text);
ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.Text);
ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandShaking.Text);
ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);
ComPort.Open();
}
elseif (btnPortState.Text == "Open")
{
btnPortState.Text = "Closed";
ComPort.Close();
}
}
privatevoid rtbOutgoing_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) // enter key
{
ComPort.Write("\r\n");
rtbOutgoing.Text = "";
}
elseif (e.KeyChar < 32 || e.KeyChar > 126)
{
e.Handled = true; // ignores anything else outside printable ASCII
range
}
else
{
ComPort.Write(e.KeyChar.ToString());