Sending string by serial port



  • Hi Pros,
    i have a problem with sending a string by the serial port.
    It´s just a little "hello-World" program...

    The port opens correctly, i´m sending a constant string after opening:

    serial->write("Hello World!\n");

    In the UI i´ve created a slider and a label. For the slider i´ve created a slot:

    connect(ui->slider_1, SIGNAL(valueChanged(int)), this, SLOT(slider_changed(int)));

    And this is the subroutine called by the slot:

    void MainWindow::slider_changed(int value)
    {
    QString buffer = QString("%1\n").arg(QString::number(value));
    serial->write((char*)buffer.data(), buffer.length());
    serial->QSerialPort::waitForBytesWritten(-1);
    ui->test_label->setText(buffer);
    }

    So far, so good. The program compiles fine, the "Hello World" is send. I´ve connected two FTDI on different USB-Ports and control the output via a terminal.

    As soon as i slide the slider the label is changed to the integer value of the slider (0-255).
    BUT: On the serial port i just receive something like "4.14.0". The \n isn´t send at all.
    I tried already to fill the buffer via sprintf, exactly the same problem.

    What is the problem???
    Hope you can help me,
    thanks

    Tobias



  • Mayby try:
    serial->write( buffer.toStdString().c_str(), buffer.size() );



  • @michelson said:

    serial->write( buffer.toStdString().c_str(), buffer.size() );

    Tanks a lot! Now it works fine :)


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    There's no need to use QString and all these conversions. You should use QByteArray directly. Something like:

    QByteArray buffer = QByteArray::number(value) + "\n";
    serial->write(buffer);
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.