1

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!

  • At first, **REMOVE** the `return 0` from `SLOT` `int MainWindow::serialReceived()`. – KernelPanic Aug 22 '16 at 19:36
  • Thanks for the comment, just edited the question changing serialReceived to void. – user6745003 Aug 22 '16 at 19:42
  • 2
    Don't you want to append to the file with `QIODevice::ReadWrite|QIODevice::Append` instead of truncating the existing file with `QIODevice::ReadWrite` http://stackoverflow.com/a/13856845/487892 – drescherjm Aug 22 '16 at 20:58

1 Answers1

1

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)
{
    ...
}
talamaki
  • 5,324
  • 1
  • 27
  • 40