How to read and write arrays of bytes on serial port in C/C++

Introduction

This page explains how to read and write arrays of bytes using the Serialib library. Serialib is a cross-platform library written in C++.

The library has been tested on Windows and Linux. This project has been developed with Qt Creator and succesfully compile with:

rightBytes

int serialib::writeBytes(const void *Buffer, const unsigned int NbBytes)

The Serialib class has a writeBytes() method that expect two parameters:

writeString() return an integer:

readBytes

int serialib::readBytes ( void *buffer,
                          unsigned int maxNbBytes,
                          unsigned int timeOut_ms, 
                          unsigned int sleepDuration_us);

The readBytes() method reads an array of maxNbBytes bytes on the serial device. This method expects two mandatory and two optional parameters:

The function returns the number of bytes read when succesfull.

If a problem happens, the function returns one of the following values:

Example

The following example send an array of 8 bytes. And then try to read 8 bytes on the serial device. This example has been tested with an Arduino that returns each byte received multiply by two. Download the full example on Github.

// Serial object
serialib serial;

// Connection to serial port
char errorOpening = serial.openDevice(SERIAL_PORT, 115200);

// If connection fails, return the error code otherwise, display a success message
if (errorOpening!=1) return errorOpening;
printf ("Successful connection to %s\n",SERIAL_PORT);

// Create an array of bytes
unsigned char prime[8] = { 1, 3, 5, 7, 11, 13, 17, 19 };

// Write the array on the serial device
serial.writeBytes(prime, 8);
printf ("Data sent\n");

// Read the bytes
unsigned char received[8];
serial.readBytes(received, 8, 2000, 1000);

// Display each byte received
for (int i=0; i<8 ; i++)
    printf("Receive [%d] = %d\n", i, received[i]);

// Close the serial device
serial.closeDevice();

return 0 ;

Arduino code

Here is the Arduino code used for checking the example:

// Setup, initialize
void setup() {
  Serial.begin(115200);
}

// Loop forever
void loop() {
  // If serial data is pending, read, write twice the received byte
  if (Serial.available())
    Serial.write( 2*Serial.read() );
}

Output

If everything is fine, the C code should display something like:

Successful connection to /dev/ttyACM0
Data sentReceive [0] = 2
Receive [1] = 6
Receive [2] = 10
Receive [3] = 14
Receive [4] = 22
Receive [5] = 26
Receive [6] = 34
Receive [7] = 38

See also


Last update : 04/04/2023