6.c. Writing PC Software to Use a Serial Port

You can write your own computer program that communicates with a serial port. The freely available Microsoft .NET framework contains a SerialPort class that makes it easy to read and write bytes from a serial port. Here is some example C# .NET code that uses a serial port:

// Choose the port name and the baud rate.
System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort("COM4", 115200);

// Connect to the port.
port.Open();

// Transmit two bytes on the TX line: 1, 2
port.Write(new byte[]{1, 2}, 0, 2);

// Wait for a byte to be received on the RX line.
int response = port.ReadByte();

// Show the user what byte was received.
MessageBox.Show("Received byte: " + response);

// Disconnect from the port so that other programs can use it.
port.Close();