Tag Archives: SerialPort

That, SerialPort stuff

The log files reveal that a lot of people are looking for help using the Serialport component of the .Net Framework. Once again, lets summarize:

  • There are two ways to access data from a serialport:
    1. Using the DataReceived event (non-blocking)
    2. Using (individual) ReadLine statements in your code (blocking)
    For a more detailed description, I mentioned the difference in a different posting. Which method you’re going to use depends on how or when data becomes available to you and where you want that data to appear in your application. If your GUI needs to be updated frequently, use non-blocking. Note that you can mix ReadLine statements in your DataReceived events, but most likely you will need to clear your serial port buffers before closing off the program.
  • Know the difference between the various way of reading data (Read, ReadLine and ReadExisting). Experiment with them.
  • If you need to read a certain amount of bytes, check into the BytesToRead property.
  • If you’re going to use blocking methods, make sure to adjust both read and write timeouts appropriately.

SerialPort and C#

What you need to know before you plan to work on Serial port communication:

0. Create a good test environment. You may need com0com (earlier) which can simulate a loopback between 2 ports.

1. Carefully choose between non-blocking and blocking. You save yourself a lot of pain when you thought using non-blocking was going to make work a lot easier. If you’re not familiar with the blocking vs. non-blocking approach, consider the table below the fold. (More on blocking vs. non-blocking). Holy wars have been fought between proponents of either form.

2. While doing your serial port stuff, also note that ReadLine has a BLOCKING nature. This is not mentioned in the original FrameWork SDK help files, but yes, it is mentioned in the SDK online. There’s no problem using ReadLine in your OnDataReceived event, but you must clear the port’s/socket buffer first before you can close your port/application (you’ll get specific errors).

3. There is no 4.

Continue reading