The Serial Port is probably the most used interface port. When we talk about the Serial Port, in most cases we talk of the port defined in the RS-232 standard. The Serial Port is found on almost every micro controller, many personal computers and terminals.
The RS-232 device connects two devices to each other. The standard has two types of devices Data Terminal Equipment (DTE) and Data Communications Equipment (DCE). The transmit wire (TxD) sends data from the DTE to the DCE and the recieve wire (RxD) sends data from the DCE to the DTE.
The RS-232 is fully asynchronous, allowing data to be transmitted and sent at the same time.
Contents |
Below you can see the SerialPort class description:
public class SerialPort : IDisposable { // Events public event SerialDataReceivedEventHandler DataReceived; public event SerialErrorReceivedEventHandler ErrorReceived; // Constructor public SerialPort(string portName); public SerialPort(string portName, int baudRate); public SerialPort(string portName, int baudRate, Parity parity); public SerialPort(string portName, int baudRate, Parity parity, int dataBits); public SerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits); // Methods public void Open(); public void Close(); public extern int Read(byte[] buffer, int offset, int count); public extern int Write(byte[] buffer, int offset, int count); public void DiscardInBuffer(); public void DiscardOutBuffer(); public void Dispose(); // Properties public int BaudRate { get; set; } public int BytesToRead { get; } public int BytesToWrite { get; } public int DataBits { get; set; } public Handshake Handshake { get; set; } public bool IsOpen { get; } public Parity Parity { get; set; } public string PortName { get; } public int ReadTimeout { get; set; } public StopBits StopBits { get; set; } public int WriteTimeout { get; set; } }
When using the serial port you have a number of settings
Which settings you need depends on the device you want to communicate with. In most manuals the settings are shortened to something like this: 4800, 8N1 which means a baud rate of 4800bps, 8 Data bits, No parity bit and 1 stop bit.
The SerialPort Class is included in the System.IO.Ports name space. This name space is included in the Microsoft.SPOT.Hardware.SerialPort assembly.
To create a new port "COM2" with a baud rate of 4800bps, 8 Data bits, No parity bit and 1 stop bit you can use:
Serial1 = new SerialPort("COM2", 4800, Parity.None, 8, StopBits.One);
To allow you to send and receive data you have to Open the serial port like this:
Serial1.Open();
To free the SerialPort you have to close it like this:
Serial1.Close();
The SerialPort can be read in an event-driven manner. When the SerialPort is open and data is received an DataReceived event is triggered. The BytesToRead property of the SerialPort holds the number of bytes that are available in the input buffer.
One tip: Add the Event handler after the Open method is called, because the Event handler gets corrupt on some systems after calling Open (Source: .NET Micro Framework newsgroup)
Below is an example program, it creates a new SerialPort, with a baud rate of 4800bps, 8 Data bits, No parity bit and 1 stop bit. It creates a new event handler that outputs the received bytes to the debug output. The main program sleeps infinitely:
using System;
using System.Text;
using System.Threading;
using System.IO.Ports;
using Microsoft.SPOT;
public class Program
{public static SerialPort Serial1;
public static void Main()
{Serial1 = new SerialPort("COM2", 4800, Parity.None, 8, StopBits.One);
Serial1.Open();
Serial1.DataReceived += new SerialDataReceivedEventHandler(Serial1_DataReceived);
// Infinite sleepThread.Sleep(-1);
}static void Serial1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{ // Check if Chars are receivedif (e.EventType == SerialData.Chars)
{ // Create new bufferbyte[] ReadBuffer = new byte[Serial1.BytesToRead];
// Read bytes from bufferSerial1.Read(ReadBuffer, 0, ReadBuffer.Length);
// Encode to stringDebug.Print(new String(Encoding.UTF8.GetChars(ReadBuffer)));
} }}
Sending data is very easy, You can write bytes with SerialPort.Write. Below is an example. It creates a new SerialPort with a baudrate of 4800bps, 8 Data bits, No parity bit and 1 stop bit. Next it creates a byte[] array from the String "Hello World!". The bytes are sent to the SerialPort and the port is closed.
// Open Serial PortSerial1 = new SerialPort("COM2", 4800, Parity.None, 8, StopBits.One);
Serial1.Open();
// Write Hello World!byte[] DataToSend = Encoding.UTF8.GetBytes("Hello World!");
Serial1.Write(DataToSend, 0, DataToSend.Length);
// Close Serial PortSerial1.Close();
To signal that a device is ready to send or receive data there are some additional signals available. The .NET Micro Framework supports two kinds of Handshaking:
The first handshaking method uses two extra signal wires, Ready To Send and Clear To Send. The RTS signal gets high when data is available for transmission. If the input buffer becomes full, the RTS wire will be set to low and high again when the input buffer space is available again. The RTS (DTE) signal is connected to the CTS signal of the DCE.
The second type of handshaking uses two special characters XOn and XOff. When the device is ready to receive data the XOn character is send. When the input buffer becomes full the XOff character is sent. When buffer space is available again, the device sends XOn again.
Which HandShaking method(s) can be used depends on the .NET Micro Framework device, the port that is used and the device that it is connected to. The advantage of using XOn/XOff handshaking is that it uses no extra wires. The disadvantage is that not every device supports it. When the input buffer of the receiving device is full and the device doesn't have a way to separate the XOn/XOff characters from the rest, the character can be lost and the data after it also.
To select a handshaking method set the Handshaking property after creating a SerialPort instance:
// Create Serial Port Serial1 = new SerialPort("COM2", 4800, Parity.None, 8, StopBits.One); Serial1.Handshake = Handshake.RequestToSend; Serial1.Open();
The options for the Handshaking property are: