Simple C++ class example using serial port, USB, wireless…

This entry is part 2 of 2 in the series Serial communications

This post is part of the Practical C++ programming tutorial for Bioloid

Here you can find a post serie about using serial port communications with C/C++ and C#, for Windows, Linux and microcontrollers.
This code is for Windows and Visual Studio and can be used for serial cable communications, USB2Dynamixel and indeed Zigbee:


class SerialPort {
HANDLE serialPortHandle;


int connect ();
int connect (wchar_t *device);
//int connect (char *deviceName, int baudRate, SerialParity parity);
void disconnect(void);

int sendArray(unsigned char *buffer, int len);
int getArray (unsigned char *buffer, int len);

void clear();


SerialPort::SerialPort() {
serialPortHandle = INVALID_HANDLE_VALUE;

SerialPort::~SerialPort() {
if (serialPortHandle!=INVALID_HANDLE_VALUE)

serialPortHandle = INVALID_HANDLE_VALUE;

int SerialPort::connect() {
return connect(L"COM1");

int SerialPort::connect( wchar_t* device) {
int error=0;
DCB dcb;


dcb.DCBlength = sizeof(dcb);

dcb.BaudRate = 57600;
dcb.Parity = NOPARITY;
dcb.fParity = 0;
dcb.StopBits = ONESTOPBIT;
dcb.ByteSize = 8;

serialPortHandle = CreateFile(device, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL);

if (serialPortHandle != INVALID_HANDLE_VALUE) {
else {

if (error!=0) {
else {

return error;

void SerialPort::disconnect(void) {
serialPortHandle = INVALID_HANDLE_VALUE;

//printf("Port 1 has been CLOSED and %d is the file descriptionn", fileDescriptor);

int SerialPort::sendArray(unsigned char *buffer, int len) {
unsigned long result;

if (serialPortHandle!=INVALID_HANDLE_VALUE)
WriteFile(serialPortHandle, buffer, len, &result, NULL);

return result;

int SerialPort::getArray (unsigned char *buffer, int len) {
unsigned long read_nbr;

read_nbr = 0;
if (serialPortHandle!=INVALID_HANDLE_VALUE)
ReadFile(serialPortHandle, buffer, len, &read_nbr, NULL);

return((int) read_nbr);

void SerialPort::clear() {
PurgeComm (serialPortHandle, PURGE_RXCLEAR | PURGE_TXCLEAR);
Series Navigation<< (I) Programming serial port communications

6 comments on “Simple C++ class example using serial port, USB, wireless…

  1. Aurelien says:

    Hi there, how would I use this class with the setup PC->USB2Dynamixel->Zig2Serial->Zig100 and Zig110->CM510? I am at ease with C++ but not with communication systems…Cheers and keep up the good work!

  2. It’s easy, you always use the communications (by wire or wireless) as if you were using a file, open, read, write, close commands. You should set the proper COM (Win) tty (Linux) port and the baud rate.

%d bloggers like this: