user6745003
user6745003

Reputation: 37

How to read data using QSerialPort to write to a file using QFile?

New to C++ and Qt, I'm trying to use a microcontroller to send a large set of data (made up of integers and commas) over serial to be put in a .csv file for use in Excel. My mainwindow.cpp code so far (where I've put all the action for testing purposes):

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <string>
#include <QtSerialPort/QSerialPort>
#include <QString>
#include <QTextEdit>
#include <QFile>
#include <QTextStream>

QSerialPort *serial;
using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    serial = new QSerialPort(this);
    serial->setPortName("/dev/cu.usbmodemfa131");
    serial->setBaudRate(QSerialPort::Baud9600);
    serial->setDataBits(QSerialPort::Data8);
    serial->setParity(QSerialPort::NoParity);
    serial->setStopBits(QSerialPort::OneStop);
    serial->setFlowControl(QSerialPort::NoFlowControl);
    serial->open(QIODevice::ReadWrite);
    connect(serial, SIGNAL(readyRead()), this, SLOT(serialReceived()));

}

MainWindow::~MainWindow()
{
    delete ui;
    serial->close();
}

void MainWindow::serialReceived()
{
    QString filename = "/Users/me/Documents/myFile/datacollecting.csv";
    QFile file(filename);
    QTextStream out(&file);
    file.open(QIODevice::ReadWrite);
    QByteArray ba;
    ba = serial->readAll();
    out << ba;
    file.close();
}

The code however is giving me some issues. It does not work reliably at all and in the resultant file it only stores the last 10 or so (out of several thousand) characters. I have searched around but have not found a way to properly store large chunks of data over serial. Is there a better way to achieve what I'm trying to do above? New to this so any help would be greatly appreciated!

Upvotes: 1

Views: 1224

Answers (1)

talamaki
talamaki

Reputation: 5472

As already written in comments you should open your output file in append mode by adding QIODevice::Append flag so that all data is written to the end of the file.

You can also connect to error signal where you can inspect possible errors. See serial port enums here.

connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(handleError(QSerialPort::SerialPortError)));

void MainWindow::handleError(QSerialPort::SerialPortError error)
{
    ...
}

Upvotes: 1

Related Questions