Posted inRaspberry Pi

Raspberry Qt – Part 11

Notice the emit statement in the following code snippet. This is where I chose to force in the new line character for our communications protocol.

void MainWindow::enterClicked()
{
    QByteArray msg( ui->lineEdit->text().toUtf8());
    emit sendMessage( msg + "\n");
    LogikalLogger::Instance().logString( LogikalLogger::LL_INFO, "Sending message: " + msg);
    clearText();
}

Now examine the readData() method. Notice how we append whatever came in to our internal QByteArray. Once that is done we search the buffer to see if our new line character is present. If it is we pull that chunk out of our internal buffer and emit a signal that a slot in our GUI will catch, ultimately displaying the text if it is printable. Index positions are zero based, but the character counts provided to both left() and remove() are actual counts so we have to add 1 to get the new line character.

void SerialThread::readData()
{
    if (!shuttingDown())
    {
        QByteArray data = m_serialPort->readAll();
        m_dataBuffer.append( data);

        int x = m_dataBuffer.indexOf('\n');
        if (x > -1)
        {
            QString msg( m_dataBuffer.left(x+1));
            LogikalLogger::Instance().logString(LogikalLogger::LL_DEBUG, "SerialThread received data: " + msg);
            emit messageReceived( msg);
            m_dataBuffer.remove(0,x+1);

        }
    }
    else
    {
        nukeServer();
    }
}

This simple example provides the basic tools you need for serial communications. All you have to do is devise your messaging protocol. It should be rather easy for you to manipulate your own buffer to support any protocol you come up with.