CSerial - A C++ Class for Serial Communications

This article was contributed by Tom Archer and Rick Leinecker.


This class is meant as a very simple alternative to the more robust, feature-rich CSerialPort class presented by Remon Spekreijse. In other words, if you need a very simple class to read or write data to the serial port, then this class might be perfect for you. However, if you need more control over just how the serial communications is to be conducted, then Remon's very fine class will probably be what you want.


Common uses of remote communications are business applications that link differnet sites in order to keep tabs on inventories and transactions. For example, I once wrote a large drug-dispensing proram in which many clinic sites automatically received new orders and updated pharmacy information each evening from a centry host location. The centry host gets inventory levels and transaction information from each site during evening hours. A large part of my time was spent construction telecommunications routines that sent and received information packets. To that extent, I offer this simple CSerial class in the hopes that it will save someone from the grungy world of serial communications that I had to endure and will free your mind up to concentrate on the problem domain.

CSerial class member functions

  • CSerial::CSerial() -
  • CSerial::CSerial() - Basic c'tor that takes no arguments.
  • CSerial::Open(int nPort = 2, int nBaud = 9600 ) - This member function is used to open the serial port. It takes two interger arguments. The first argument contains the port number where the valid entries are 1 through 4. The second argument is the baud rate. Valid values for this argument are 1200, 2400, 4800, 9600, 19200, 38400 and 76800. This function returns TRUE if successful. Otherwise, it returns a value of FALSE.
  • CSerial::Close() - While the d'tor will automatically close the serial port for you, this function has been added just in case there is a reason that you need to explicit close the port.
  • CSerial::SendData(const char *, int) - This function writes data from a buffer to the serial port. The first argument it takes is a const char* to a buffer that contains the data being sent. The second argument is the number of bytes being sent. This function will return the actual number of bytes that are succesfully transmitted.
  • CSerial::ReadDataWaiting(void) - This function simply returns the number of bytes that waiting in the communication port's buffer. It basically allows you to "peek" at the buffer without actually retrieving the data.
  • CSerial::ReadData(void*, int) - This function reads data from the port's incoming buffer. The first argument that it takes is a void* to a buffer into which the data will be placed. The second argument is an integer value that gives the size of the buffer. The return value of this function contains the number of bytes that were successfully read into the provided data buffer.

Example Usage

Here are some examples of how easy it is to use this class.

Opening the serial port

CSerial serial;
if (serial.Open(2, 9600))
 AfxMessageBox("Port opened successfully");
 AfxMessageBox("Failed to open port!");

Sending Data

CSerial serial;
if (serial.Open(2, 9600))
 static char* szMessage[] = "This is test data";
 int nBytesSent = serial.SendData(szMessage, strlen(szMessage));
 ASSERT(nBytesSent == strlen(szMessage));
 AfxMessageBox("Failed to open port!");

Reading Data

CSerial serial;
if (serial.Open(2, 9600))
 char* lpBuffer = new char[500];
 int nBytesRead = serial.ReadData(lpBuffer, 500);
 delete []lpBuffer;
 AfxMessageBox("Failed to open port!");


Download source - 2 Kb


  • No received data

    Posted by Mord on 07/15/2016 06:51am

    The problem is that the variable ComStat.cbInQue in function "ReadData" is always equal to zero ...so the nBytesRead are nulL!

  • No received data

    Posted by Mord on 07/15/2016 06:41am

    Hi, my board is connected to the computer and COM port 3 is assigned to it. After running your program, the COM port is opened SUCCESSFULLY but the "nBytesRead" variable is always equal to 0 and so im not able to print any received data from the device. Any recommendations? Thanks

  • Posted by fourfaith apple on 07/13/2016 11:44pm

    Debug Assertion Failed!" message at "ASSERT(nBytesSent == strlen(szMessage))

  • Using for reading a COM port connected to bluetooth module HC-05

    Posted by James on 04/20/2016 12:36pm

    In arduino IDE i can read the data coming through on COM38 just fine but when I used this code it fails to open. Is this code compatible for reading from a serial port connected to bluetooth? I have set the baud rate to 9600 which is the same as what the HC-05 is using

    • the fix for that COM10 and beyond

      Posted by jamez on 06/02/2016 12:28pm


    • MR

      Posted by Josh on 05/24/2016 11:52am

      You are not able to go past COM9 with this library. It says valid comm ports are 1-4 but up to 9 seems to work. Passed that tho it wont work as is.

  • Student

    Posted by Yousif on 02/25/2016 09:49am

    How can i install this library in raspberry Pi?

  • TX Speed

    Posted by Dierk Reuter on 11/28/2015 10:49pm

    This all works very nicely. The problem that I am running into is speed. I am connecting at a baud rate of 115200 and get transmissions speeds of 320 B/s with null modem cable. I ran some experiments with "Com Port Stress Test" and it turns out the speed dramatically falls when sending small sets of bytes. With larger sets my desktop goes up 10kB/s. I should mention that I am using usb to serial cables. Not sure if that matters. Looking for hints on how one might crank up the tx speed.

  • Mr.

    Posted by David on 05/10/2015 11:15pm

    I am trying to use your CSerial to communicate via the COM port: 1. Are there anything more approate to be used instead nowadays? 2. I need to use BAUD rate of 115200 and .Open(1, 115200) fail. What should I do to make it work? Thanks

    • Dont use Com Port 1

      Posted by Dan Kay on 10/27/2015 09:03am

      The computer usually reserves COMPORT 1 for internal communications between things attached to motherboard, or are configured for a printer that you no longer have installed or attached but the configuration is still there. If your device gets assigned COMPORT 1 reassign your device COMPORT in Device Manager. I usually start with ComPort 3 and go up.

  • serial communication using opencv with GCC compiler and Cmake

    Posted by lakshya on 04/14/2015 11:07pm

    Hi,I am doing a project wherein I need to send the image to serial port. But i am using opencv with GCC Compiler and Cmake. Can i plz know whats the API for transfering the image. Plz help me,i am new to opencv.

  • Assertion Failed

    Posted by deno on 04/14/2015 01:22am

    Hi, I try to send a letter followed by 7 digit number like "D0150000". I converted them to "const char*". However I always get "Debug Assertion Failed!" message at "ASSERT(nBytesSent == strlen(szMessage));". Can you help me with that? Thanks in advance.

  • valid baud

    Posted by SChalice on 02/15/2015 03:42pm

    "Valid values for this argument are 1200, 2400, 4800, 9600, 19200, 38400 and 76800." Yeah well I need 56700 just like hyperterminal uses so I guess your program is useless for me?

    • guy who can read code

      Posted by Ben on 05/19/2015 12:10pm

      Did you try reading the source code? It will really take any number you give it. Whether the UART cooperates is a different matter.

  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date