Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Mobile and Embedded
  4. couldn't write into file
Qt 6.11 is out! See what's new in the release blog

couldn't write into file

Scheduled Pinned Locked Moved Unsolved Mobile and Embedded
8 Posts 3 Posters 798 Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Offline
    C Offline
    chandana
    wrote on last edited by SGaist
    #1

    Hi,
    I am reading the real time data from the usbto rs232 converter.The problem is i need to save all the data into a file.the problem is the file is opening but couldn't able to write the data into the file
    plz help me to resolve the issue.

    QString filename2="C:/Qt/data.txt";
    QFile wf_g(filename2);
    QTextStream wf_out(&wf_g);
    MainWindow::~MainWindow()
    {
        qDebug() << "came-50";
      //  dia_data.flush();
    //     dia_data.close();
         wf_g.flush();
         wf_g.close();
        serial->close();
        arduino->close();
        delete ui;
    }
    
    if(g_i==0)
        {
            if(!wf_g.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
            {
                  qDebug() << "Could not open for writing\n";
                  //return 0;
            }
    
            if(!dia_data.open(QIODevice::WriteOnly | QIODevice::Text| QIODevice::Append))
            {
                   qDebug() << "Could not open for writing\n";
                   // return 0;
            }
    
    
    
            g_i=1;
       }
    wf_out << "\nData-1  = " << dataval << "\n";
    

    [edit: Added missing coding tags SGaist]

    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      The code you posted is incomplete. We don't know when the files are opened, when they are written to nor how you are handling your serial port.

      Since you post the destructor of your MainWindow class and some free running lines, it could be very well that you are initialising local files somewhere while trying to write to file class member variables which have neither been initialised nor been opened.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      2
      • C Offline
        C Offline
        chandana
        wrote on last edited by
        #3

        //24-4-18-- works ok. some packet drop is there in wave graph. data and status file not updating.
        //to get data in file, u have to open everytime inside while loop and close at the end of while loop.
        // while(1){ if(bytes there) {} close file }//end of while

        #include "mainwindow.h"
        #include "ui_mainwindow.h"
        #include "qcustomplot.h"
        #include <QFile>
        #include <QCoreApplication>
        #include <QTextStream>
        #include <QSerialPort>
        #include <QSerialPortInfo>

        //-------------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------

        QString filename2="C:/Qt/data.txt";
        QFile wf_g(filename2);
        QTextStream wf_out(&wf_g);

        QString filename="C:/Qt/Dataoutput1.txt";
        QFile dia_data(filename);
        QTextStream dia_out(&dia_data);

        int g_i=0;
        int key=0;
        double j=0;
        double k=0;
        QString dataval,dataval1;
        bool servo_run=false;
        //-------------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------------
        //----------------------------------------------------------------------------------------------------------------

        MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
        {

        ui->setupUi(this);
        ui->Diameterdata->display("------");
        ui->position->display("------");
        serial= new QSerialPort(this);
        arduino= new QSerialPort(this);
        arduino_is_available=false;
        serial->setPortName("COM22"); //port where the model 600 is connected.
        serial->open(QIODevice::ReadOnly);
        serial->setBaudRate(QSerialPort::Baud38400);
        serial->setDataBits(QSerialPort::Data8);
        serial->setParity(QSerialPort::EvenParity);
        serial->setStopBits(QSerialPort::OneStop);
        serial->setFlowControl(QSerialPort::NoFlowControl);
        

        // qDebug()<< "NUMBER OF AVAILABLE PORTS:"<<QSerialPortInfo::availablePorts().length();
        /* foreach(const QSerialPortInfo &serialPortInfo,QSerialPortInfo::availablePorts())
        {
        qDebug()<<"has vendor ID"<<serialPortInfo.hasVendorIdentifier();
        if(serialPortInfo.hasVendorIdentifier())
        {
        qDebug()<<"vendor id"<<serialPortInfo.vendorIdentifier();
        }
        qDebug()<<"has product id"<<serialPortInfo.hasProductIdentifier();
        if(serialPortInfo.hasProductIdentifier())
        {
        qDebug()<<"product id"<<serialPortInfo.productIdentifier();
        }
        }*/
        foreach(const QSerialPortInfo &serialPortInfo,QSerialPortInfo::availablePorts())
        {
        if(serialPortInfo.hasVendorIdentifier()&&serialPortInfo.hasVendorIdentifier())
        {
        if(serialPortInfo.vendorIdentifier()==arduino_uno_vendor_id)
        {
        if(serialPortInfo.productIdentifier()==arduino_uno_product_id)
        {
        arduino_port_name=serialPortInfo.portName();
        arduino_is_available=true;
        }
        }
        }
        }
        if(arduino_is_available)
        {
        arduino->setPortName(arduino_port_name);
        arduino->open(QIODevice::ReadWrite);
        arduino->setBaudRate(QSerialPort::Baud9600);
        arduino->setDataBits(QSerialPort::Data8);
        arduino->setParity(QSerialPort::NoParity);
        arduino->setStopBits(QSerialPort::OneStop);
        arduino->setFlowControl(QSerialPort::NoFlowControl);
        connect(arduino, SIGNAL(readyRead()), this, SLOT(receive()));
        qDebug()<<"port opened";
        }

        ui->customPlot->addGraph();
        /*
        ui->customPlot->xAxis2->setRange(1,10);
        ui->customPlot->xAxis2->setVisible(true);
        ui-> customPlot->xAxis2->setTicks(true);
        ui->customPlot->xAxis2->setSubTicks(true);
        ui->customPlot->xAxis2->setTickLabels(true);*/
        ui->customPlot->axisRect()->setupFullAxesBox();
        QSharedPointer<QCPAxisTicker> ticker(new QCPAxisTicker);
        ui->customPlot->yAxis->setTicker(ticker);
        ticker->setTickCount(10); // tick step shall be 1.0
        QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
        ui->customPlot->xAxis->setTicker(timeTicker);
        timeTicker->setTimeFormat("%m:%s");
        ui->customPlot->axisRect()->setupFullAxesBox();
        ui->customPlot->xAxis->setTickLengthOut(5);
        ui->customPlot->yAxis->setRange(-0.3000,0.4000);
        QSharedPointer<QCPAxisTickerFixed> fixedTicker(new QCPAxisTickerFixed);
        ui->customPlot->xAxis2->setTicker(fixedTicker);
        fixedTicker->setTickStep(6);
        ui->customPlot->xAxis2->setTickLabels(true);
        ui->customPlot->xAxis2->setVisible(true);
        ui->customPlot->xAxis2->setSubTicks(false);
        ui->customPlot->xAxis2->setRange(1,100);
        ui->customPlot->xAxis2->setLabel("Length\n");
        ui->customPlot->xAxis->setLabel("Time in seconds\n");
        connect(serial, SIGNAL(readyRead()), this, SLOT(receive()));
        

        }
        //---------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------

        MainWindow::~MainWindow()
        {
        qDebug() << "came-50";
        /* dia_data.flush();
        dia_data.close();*/
        wf_g.flush();
        wf_g.close();
        serial->close();
        arduino->close();
        delete ui;
        }
        //---------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------

        void MainWindow::receive()
        {

        disconnect(serial,SIGNAL(readyRead()),0,0);
        //disconnect(serial,0,receive,0);
        
        qDebug() << "CAME TO RECIEVE\n";
        
        if(g_i==0)
        {
            if(!wf_g.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
            {
                  qDebug() << "Could not open for writing\n";
                  //return 0;
            }
        
            if(!dia_data.open(QIODevice::WriteOnly | QIODevice::Text| QIODevice::Append))
            {
                   qDebug() << "Could not open for writing\n";
                   // return 0;
            }
        
        
        
            g_i=1;
        

        }

        while(1)
        {
            if (serial->bytesAvailable()>0||serial->waitForReadyRead(10))
            {
        
              if (arduino->isOpen() && arduino->isWritable()&&servo_run==false)
                  {
                    QByteArray ba("56");
                    qDebug()<<"aurdino port ";
                   //QString dat1 =arduino->readAll();
                    //qDebug()<<"wrote="<<dat1;
                    arduino->write(ba);
                    arduino->flush();
                    servo_run=true;
                  }
                 QByteArray ba1;
                 ba1.resize(9);
                 ba1=serial->read(9);
                 qDebug() << "original-wave1------------------" <<ba1;
                 QString dataval(ba1.toHex().toUpper());
                wf_out << "\nData-1  = " << dataval << "\n";
        
                 dataval1=dataval;
                 //qDebug() << "string data1---" <<dataval1;
                 dataval1.remove(0,2);
                 dataval1.remove(6,10);
                 dataval1.insert(2,".");
                 //qDebug() << "string data2---" <<dataval1;
                 MainWindow::updateLCD1(dataval1);
                dataval.remove(0,8);
              // qDebug() << "Final data------------------" <<dataval;
               dataval.remove(6,4);
              // qDebug() << "Final data1------------------" <<dataval;
               dataval.insert(2,".");
              // qDebug() << "Final data4------------------" <<dataval;
               MainWindow::updateLCD(dataval);
              // j=wave.wf1.toDouble(&wf_ok);
                j=dataval.toDouble();
             // qDebug() << "Final data3------------------" <<j;
                      k=j;
                      j=j/2;
               wf_out << "\nData-2 = " << j<< "\n";
        
                 dia_out << "\nDat1  = " << j << "\n";
        
                      k=-k/2;
                 dia_out << "\nDat2  = " <<k << "\n";
        
                     qDebug() << "\n output      = " << j ;
                     qDebug() << "\n output1      = " << k ;
                     static QTime time(QTime::currentTime());
                     // qDebug() << "time=" <<time;
                     // calculate two new data points:
                      double key = time.elapsed()/1000.0; // time elapsed since start of demo, in seconds
                      //qDebug() << "time1=" <<key;
                      static double lastPointKey = 0;
                      if (key-lastPointKey > 0.002) // at most add point every 2 ms
                      {
                       ui->customPlot->graph(0)->addData(key, j);
                       ui->customPlot->addGraph();
                       ui->customPlot->graph(1)->addData(key, k);
                       //key++;
                       ui->customPlot->xAxis->setRange(key,10, Qt::AlignRight);
                       ui->customPlot->xAxis2->setRange(key,10, Qt::AlignRight);
                       ui->customPlot->axisRect()->setupFullAxesBox(true);
                       ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
                       ui->customPlot->replot();
                       lastPointKey = key;
        
                     }
        

        } //-------------------------- if condition serial bytes available------------------------
        }
        }

        void MainWindow::updateLCD(const QString sensorread)
        {
        ui->Diameterdata->display(sensorread);
        }

        void MainWindow::updateLCD1(const QString sensorread1)
        {
        ui->position->display(sensorread1);
        }
        /void MainWindow::receivedata()
        {
        QByteArray ba("R");
        qDebug()<<"aurdino port ";
        QByteArray dat1 =arduino->readAll();
        qDebug()<<"wrote"<<dat1;
        arduino->write(ba);
        }
        /

        this is mainwindow.cpp file
        #include "mainwindow.h"
        #include <QApplication>

        int main(int argc, char *argv[])
        {
        QApplication a(argc, argv);
        MainWindow w;
        w.resize(800, 500);
        w.show();

        return a.exec();
        

        }
        this is main.cpp file

        1 Reply Last reply
        0
        • SGaistS Offline
          SGaistS Offline
          SGaist
          Lifetime Qt Champion
          wrote on last edited by
          #4

          Why are you disconnecting your serial port and then use an infinite loop in your GUI thread ?

          Interested in AI ? www.idiap.ch
          Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

          1 Reply Last reply
          1
          • C Offline
            C Offline
            chandana
            wrote on last edited by
            #5

            If i don't disconnect the serial port it is breaking the infinite while loop .So i am disconnecting the serial port

            1 Reply Last reply
            0
            • C Offline
              C Offline
              chandana
              wrote on last edited by
              #6

              I tried all the possible way plz help me to resolve this issue

              Pablo J. RoginaP 1 Reply Last reply
              0
              • SGaistS Offline
                SGaistS Offline
                SGaist
                Lifetime Qt Champion
                wrote on last edited by
                #7

                Well: use the asynchronous nature of QSerialPort and not an infinite loop.

                Interested in AI ? www.idiap.ch
                Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                1 Reply Last reply
                2
                • C chandana

                  I tried all the possible way plz help me to resolve this issue

                  Pablo J. RoginaP Offline
                  Pablo J. RoginaP Offline
                  Pablo J. Rogina
                  wrote on last edited by
                  #8

                  @chandana have you checked the terminal example of QSerialPort?

                  You may check how they read the incoming data, and eventually adapt such method to save to file what's received.

                  Upvote the answer(s) that helped you solve the issue
                  Use "Topic Tools" button to mark your post as Solved
                  Add screenshots via postimage.org
                  Don't ask support requests via chat/PM. Please use the forum so others can benefit from the solution in the future

                  1 Reply Last reply
                  1

                  • Login

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • Users
                  • Groups
                  • Search
                  • Get Qt Extensions
                  • Unsolved