Serial ports using System.IO.Ports
suggest changeIterating over connected serial ports
using System.IO.Ports;
string[] ports = SerialPort.GetPortNames();
for (int i = 0; i < ports.Length; i++)
{
Console.WriteLine(ports[i]);
}
Instantiating a System.IO.SerialPort object
using System.IO.Ports;
SerialPort withDefaults = new SerialPort();
SerialPort named = new SerialPort("COM1");
SerialPort namedAt9600 = new SerialPort("COM1", 9600);
NOTE: Those are just three of the seven overloads of the constructor for the SerialPort type.
Reading/Writing data over the SerialPort
The simplest way is to use the SerialPort.Read and SerialPort.Write methods. Read may return fewer bytes than requested. You can also use the System.IO.Stream from SerialPort.BaseStream.
Reading
int length = port.BytesToRead;
//Note that you can swap out a byte-array for a char-array if you prefer.
byte[] buffer = new byte[length];
int bytesRead = port.Read(buffer, 0, length);
You can also read all data available:
string curData = port.ReadExisting();
Or simply read to the first newline encountered in the incoming data:
string line = port.ReadLine();
Writing
The easiest way to write data over the SerialPort is:
port.Write("here is some text to be sent over the serial port.");
You can also send bytes:
//Note that you can swap out the byte-array with a char-array if you so choose.
byte[] data = new byte[1] { 255 };
port.Write(data, 0, data.Length);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents