How to read and write strings on serial port in C/C++

Introduction

This page explains how to read and write strings 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:

writeString

int serialib::writeString(const char *String);

The Serialib class has a writeString() method that expect one parameters: a string.

The string is expected to be a Null-terminated string. Note that the null character does not belong to the string, so it is not sent to the serial device.

writeString() return an integer:

readString

int serialib::readString  ( char *receivedString,
                            char finalChar,
                            unsigned int maxNbBytes,
                            const unsigned int timeOut_ms=0);

The readString() method reads a string on the serial device. This method expects three mandatory and one optional parameters:

The function returns the number of bytes read (including the null character) when successful.

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

Example

The following example writes a string terminated by a carriage return. And then read the string received on the serial device. This example has been tested with an Arduino that returns each character received on Serial after capitalizing it. 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 the string
char buffer[15] = "hello\n";

// Write the string on the serial device
serial.writeString(buffer);
printf ("String sent: %s", buffer);

// Read the string
serial.readString(buffer, '\n', 14, 2000);
printf("String read: %s\n", buffer);

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

return 0 ;

Arduino code

Here is the Arduino code used for checking the example:

// Return the returns the character received on Serial after capitalizing it
// More details on:
// https://lucidar.me/en/serialib/cross-plateform-rs232-serial-library/

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

// Loop forever
void loop() {
  // If serial data is pending, read, capitalize and write the character
  if (Serial.available())
    Serial.write( toupper (Serial.read()) );
}

Output

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

Successful connection to /dev/ttyACM0
String sent: hello
String read: HELLO

See also


Last update : 04/04/2023