CSerial - A C++ Class for Serial Communications

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

  • 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

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

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

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

      Reply
    Reply
  • Sailor

    Posted by Bob Brunius on 02/13/2015 09:58pm

    Who do you detect that a port has been disconnected after it had been successfully opened?

    Reply
  • Block on Read

    Posted by Justyn on 01/13/2015 08:51pm

    I'm new to programming in Windows, and what I'm looking for seems to be hard to find. Does anyone know how to change the timeouts such that I block indefinitely on read, but I still have overlapping IO? (ie full duplex support).

    Reply
  • Thanks

    Posted by Chris Conn on 11/14/2014 11:33pm

    I made a few changes to compile for Rad Studio XE6. I added #include . I changed BOOLs to ints. I had to format string/chars as Wides using L() macro - i.e L("Failed to open port") Don't forget to include the files in your build too. So I am successfully connecting to a comport but I am having some issues with sending data. I don't have a good way to test other than my device at the moment so I am not 100% sure something else isn't going on but I do suspect it may be something with the configuration/modification of the code. I use serial.SendData(buf,6) where: char buf[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; Any thoughts on where to start looking?

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