reading from Serial port and writing data to a file



  • I find it strange. I can read from the serial port and I can see that data is read in the application output window. There is no error, meaning it is writing to the file, But when I check the file, there is nothing in it. Can someone suggest me why this is happening ? thanks!

    void MainWindow::readSerial()
    {
    QStringList buffer_split = serialBuffer.split(";");

    if(buffer_split.length()<4)
    {
        serialData = Board->readAll();
        serialBuffer = serialBuffer + QString::fromStdString(serialData.toStdString());
        serialData.clear();
    }
    else
    {
        serialBuffer = "";
        qDebug() <<QDateTime::currentDateTime().toString("hh:mm:ss.zzz")<<endl;
        qDebug() <<"Buffer Split ="<<buffer_split<<endl;  
        sensor_Value= (buffer_split[0]).toDouble();;       
        qDebug() <<"Sensor Value= "<<sensor_Value<<endl;
    

    /* Write buffer to the file */
    QFile file("data.txt");
    QString input;
    QTextStream stream (&file);
    input = sensor_Value;
    while(file.open(QIODevice::WriteOnly|QIODevice::Text|QIODevice::Append))
    {
    stream<<input;
    }
    file.close();
    }
    }


  • Lifetime Qt Champion

    Hi,

    The correct flow for QTextStream is rather:

    QFile data("data.txt");
    if (data.open(QFile::WriteOnly | QFile::Truncate)) {
        QTextStream out(&data);
        out << sensor_Value;
    } else {
        qDebug() << "Failed to open file" << data.error();
    }
    

    On a side note, why not just do serialData += Board->readAll(); ? You're doing multiple useless conversions.

    [edit: Fixed code SGaist]


  • Qt Champions 2016

    @Muzab said:

    here is no error, meaning it is writing to the file

    To add to @SGaist, how do you know there's no error when no checks against the stream's status flag are made?



  • The code that I am using to write to a file works if i run it independently and it won't when I use it in my project file.
    Thanks for the corrections.

    qDebug() << "Failed to open file" << data.error(); // seems to be correct instead of data->error()
    

    The problem was with

    QString input;
    

    It was getting reinitialized each time. Sorry ! dudes.. for the blunder! I truly appreciate your kind response.


Log in to reply
 

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