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

  • 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

    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
  • Cannot convert 'char[15]' to 'wchar_t *'

    Posted by Eduardo on 10/22/2014 10:37am

    I'm using Embarcadero XE7 as compiler and I'm having this problem:Cannot convert 'char[15]' to 'wchar_t *'at lines:wsprintf( szPort, "COM%d", nPort ); m_hIDComDev = CreateFile( szPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL );

    • Re: Cannot convert 'char[15]' to 'wchar_t *'

      Posted by Srba on 05/29/2015 03:49am

      Either change type of szPort from char[15] to wchar_t[15], or live it as it is but use wsprintfA and CreateFileA instead.

      Reply
    Reply
  • beginner question

    Posted by RRR on 07/08/2014 08:30am

    Hi all, 1. I download Microsoft Visual Studio Express 2013 2. I create a new c++ Empty Project 3. import the source file to the project Result: I have lot o errors. please ca some one help me with the steps to make this works thanks. Errors: Error 1 error C1083: Cannot open include file: 'stdafx.h': No such file or directory c:\personal\projects\visual studio 2013\projects\project1\project1\serial.cpp 3 1 Project1 2 IntelliSense: identifier "BOOL" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.h 23 2 Project1 3 IntelliSense: identifier "BOOL" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.h 24 2 Project1 4 IntelliSense: identifier "BOOL" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.h 30 2 Project1 5 IntelliSense: identifier "BOOL" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.h 33 2 Project1 6 IntelliSense: identifier "HANDLE" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.h 35 2 Project1 7 IntelliSense: identifier "OVERLAPPED" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.h 36 2 Project1 8 IntelliSense: identifier "BOOL" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.h 37 2 Project1 9 IntelliSense: cannot open source file "stdafx.h" c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 3 1 Project1 10 IntelliSense: identifier "memset" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 9 2 Project1 11 IntelliSense: identifier "OVERLAPPED" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 9 40 Project1 12 IntelliSense: identifier "NULL" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 11 16 Project1 13 IntelliSense: identifier "FALSE" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 12 14 Project1 14 IntelliSense: identifier "BOOL" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 23 1 Project1 15 IntelliSense: identifier "TRUE" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 26 26 Project1 16 IntelliSense: identifier "DCB" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 30 2 Project1 17 IntelliSense: identifier "wsprintf" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 32 2 Project1 18 IntelliSense: identifier "CreateFile" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 33 16 Project1 19 IntelliSense: identifier "GENERIC_READ" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 33 36 Project1 20 IntelliSense: identifier "GENERIC_WRITE" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 33 51 Project1 21 IntelliSense: identifier "NULL" is undefined c:\Personal\Projects\visual astudio 2013\Projects\Project1\Project1\Serial.cpp 33 69 Project1 22 IntelliSense: identifier "OPEN_EXISTING" is undefined c:\Personal\Projects\visual studio 2013\Projects\Project1\Project1\Serial.cpp 33 75 Project1

    • maybe i can help you

      Posted by davide on 08/09/2014 04:17am

      step0: create stdafx.h in your project dir.. where there are serial.h , serial.cpp and your cpp main file step1: in serial.h #include #include #include step2: in your main c++ file #include "stdafx.h" #include #include "serial.h" maybe an error will remain : i'm talking about "wsprintf". to remove this error you should try to change the first parameter into TCHAR object. I solved the problem with this writing: wsprintf( tchar, L"your_text%d", your_int ); where tchar is a TCHAR object (ie: TCHAR tchar[15];) see msdn documentation sorry for the english.. i'm an italian student :)

      Reply
    Reply
  • How to set baudrate for serial port in c++

    Posted by Sushant on 07/17/2013 09:58pm

    I am start a program to set baudrate,parity,start/stop,parity bit .. but i dont understand to set baud rate????

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Thanks to the Internet of Things (IoT), physical assets are turning into participants in real-time global digital markets. The countless types of assets around us will become as easily indexed, searched and traded as any online commodity. While some industries will be tougher to transform than others – those with physical limitations, such as manufacturing, will be harder to digitize – untold economic opportunities exist for growth and advancement. Our research shows this will create a new "Economy …

  • Lenovo recommends Windows 8 Pro. "I dropped my laptop getting out of the taxi." This probably sounds familiar to most IT professionals. If your employees are traveling, you know their devices are in for a rough go. Whether it's a trip to the conference room or a convention out of town, any time equipment leaves a user's desk it is at risk of being put into harm's way. Stay connected at all times, whether at the office or on the go, with agile, durable, and flexible devices like the Lenovo® …

Most Popular Programming Stories

More for Developers

RSS Feeds

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