How To Access Serial Ports In C#

Article by:
Date Published:
Last Modified:

The pre-installed Visual Studio C# class for manipulating serial ports in C# is found in the following namespace:

1
2
// The class for manipulating serial ports in C#
System.IO.Ports.SerialPort

To get a string list of the current active COM ports on the computer, and then populate a combobox with this list, use the code:

1
2
3
// Populates a combobox with a string list of the active serial port names
// e.g. "COM3", "COM8"
ComboBoxComPorts.ItemsSource = System.IO.Ports.SerialPort.GetPortNames();

The SerialPort class contains an handy enumeration of commonly available baud rates. The following code shows how to populate a combo box with these values.

1
2
3
4
// An enumeration of common baud rates is used to populate
// a combo box.
foreach (int i in Enum.GetValues(typeof(SerialPort.BaudRate)))
    ComboBoxBaudRate.Items.Add(i);

To set up the SerialPort class for use, you have to set the parameters shown in the code below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
SerialPort serialPort;

public void ComPortSetup(
    int baudRate, 
    int numDataBits,
    string portName,
    StopBits stopBits,
    Parity parity,
    int readBufferSize) {
    this.serialPort = new SerialPort();
    // Set up serial comms
    this.serialPort.BaudRate = baudRate;
    this.serialPort.DataBits = numDataBits;
    this.serialPort.PortName = portName;
    this.serialPort.StopBits = stopBits;
    this.serialPort.Parity = parity;
    this.serialPort.ReadBufferSize = readBufferSize; //Default dataIList
}

Then you can use code like shown below to open and close the serial port for use.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Opens the port. If already open, will close first.
// If null, returns false.
public bool OpenPort() {
    try {
        if (this.IsOpen())
            this.CloseAndDisposePort();
        serialPort.Open();
    } catch (Exception e) {
        MessageBox.Show(Convert.ToString(e));
        return false;
    }

    return true;
}

/// <summary>
/// Checks whether serial port is open. 
/// </summary>
/// <returns>Returns true is serial port is open, returns false if serial port is closed or null.</returns>
public bool IsOpen() {
    if (serialPort != null)
        return serialPort.IsOpen;
    else
        return false;
}

/// <summary>
/// Closes and disposes of serial port.
/// </summary>
public void CloseAndDisposePort() {
    serialPort.Close();
    serialPort.Dispose();
}

Authors

Geoffrey Hunter

Dude making stuff.

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License .

Tags

    comments powered by Disqus