I am sending data to Arduino using QtSerialPort. When I read the data the ouput has several not printer characters. I am using a QTexEdit (in left hand) to insert the data to send and other (in right hand) to insert the data to read.

enter image description here

You can see the receive data has some no printer character.

Workflow of sending and receiving data between QtSerialPort and Arduino

Sending Data with QtSerialPort

void MainWindow::sendData(){

    QString m_allData = m_sendEdit->toPlainText();
    int i = 0;
    int size = m_allData.size();

    QString line = "";
    int c = 0;
    while(i < size){
        if(c == 24){
            int sended = m_serialPort->write(line.toUtf8(), 24);
            c = 0;
    if(c > 0){
        m_serialPort->write(line.toUtf8(), c);

I want to send the data with a buffer size of 24 bytes.

Reading and Sending Data with Arduino

 void setup() {

 void loop() {


    if (Serial.available() > 0){
        short i = 0;
        int size = Serial.available();
        String data = Serial.readString();

The Arduino code is simple.

Receiving Data with QtSerialPort

void MainWindow::readData(){
    int c = 0;
    char * dataBuffer;
    int size = m_serialPort->bytesAvailable();
    dataBuffer = new char[size];
    c = m_serialPort->read(dataBuffer, size);
    m_receiveEdit->setText(m_receiveEdit->toPlainText() + QString::fromUtf8(dataBuffer));
        delete dataBuffer;

I am trying to read the same data that I send to Arduino. What kind of convertion do I have to do?

  • There is no point in splitting your writes into 12-byte chunks. The serial port is slow, and your Qt code is fast, thus the first byte of the second chunk will come right after the last byte of the first chunk. Commented Jun 10, 2015 at 15:41

1 Answer 1


You have no warranty that Qt will receive the whole message in a single chunk. It may receive "no se" as the first chunk, and then "q pasa" as the second chunk. Since dataBuffer is dynamically allocated, it initially contains garbage, and you are printing the part of this garbage that you did not overwrite.

An easy fix would be to simply NULL-terminate the buffer:

dataBuffer = new char[size + 1];            // + 1 byte for '\0'
c = m_serialPort->read(dataBuffer, size);
dataBuffer[c] = '\0';                       // terminate the string
  • Ok, that was the problem. with dataBuffer['c'] = '\0' the output data is clean. Thank you @Edgar Bonet
    – Robert
    Commented Jun 10, 2015 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.