CSerial - A C++ Class for Serial Communications

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

This article was contributed by Tom Archer and Rick Leinecker.

Preface

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.

Introduction

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");
else
 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));
}
else
 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;
}
else
 AfxMessageBox("Failed to open port!");

Downloads

Download source - 2 Kb


Comments

  • Eng

    Posted by Tsvi Lissack on 03/23/2017 06:54am

    I recommend that you add the ability to: 1. Send a BREAK to the port (and clear the BREAK) 2. Read the status of the out-of-band lines of the port 3. Write the state of out-of-band line of the port 4. Change baud-Rate without re-initializing.

    Reply
  • bc

    Posted by fils on 01/18/2017 08:14pm

    i dont understant... when i use Open() it always go for "Failed" what am i missing?

    Reply
  • Unknow type

    Posted by Fabio on 12/24/2016 05:37am

    I try to compile but I get a lot of errors: - error: unknown type name 'HANDLE' - error: unknown type name 'BOOL' - error: unknown type name 'OVERLAPPED' - error: use of undeclared identifier 'NULL' and so on...

    • Solution Alternative

      Posted by Achmad Fathoni on 07/10/2017 08:34pm

      #include in Serial.h and Serial.cpp work for me in VS2017

      Reply
    Reply
  • 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 simmeck on 12/02/2016 02:17am

      Hello, I have the same problem like you. How have you solved it? When I write in ReadData: if(!ComStat.cbInQue) return(nBytesRead); I have also in nBytesRead a Zero. Thanks!

      Reply
    • No received data

      Posted by simmeck on 12/02/2016 02:14am

      Hello, I have the same problem like you. How have you solved it? When I write in ReadData: if(!ComStat.cbInQue) return(nBytesRead); I have also in nBytesRead a Zero. Thanks!

      Reply
    Reply
  • 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

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

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

    Reply
  • 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

      https://support.microsoft.com/en-us/kb/115831

      Reply
    • 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.

      Reply
    Reply
  • Student

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

    How can i install this library in raspberry Pi?

    Reply
  • 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.

    Reply
  • 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.

      Reply
    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

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