Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello all,

I'm developing a multi-widget Qt desktop application that serially interacts with an embedded device. I'm new to Qt and serial port application development.


I need to reuse the opened serial port instance in other forms as well for reading or writing.

Where and how I can configure the serial port in order to access it in multiple forms without repeating configuration?

for example, if I have to a connection in a second widget, how can I access the serial object??

Any help would be welcome.

What I have tried:

I created the instance in one module (.cpp file) and then export the declaration through a .h file which other modules who need to access it.

Here is the .h of the serial implementation

C++
#ifndef TETRASERIAL_H
#define TETRASERIAL_H

#include <QObject>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QDebug>

class tetraSerial : public QObject
{
    Q_OBJECT
public:
    explicit tetraSerial(QObject *parent = nullptr);
  static QSerialPort *serialObject;

signals:

public slots:
};

#endif // TETRASERIAL_H


The corresponding .cpp file as follows.

I configured the serial port in that class file. I want to call that instance in different windows.

C++
#include "tetraserial.h"

 QSerialPort *tetraSerial::serialObject;


tetraSerial::tetraSerial(QObject *parent) : QObject(parent)
{

   serialObject = new QSerialPort(this);
   serialObject->setPortName("com5");
   serialObject->setBaudRate(1000000);
   serialObject->setDataBits(QSerialPort::Data8);
   serialObject->setParity(QSerialPort::NoParity);
   serialObject->setStopBits(QSerialPort::OneStop);
   serialObject->setFlowControl(QSerialPort::HardwareControl);
   serialObject->open(QIODevice::ReadWrite);

}


I tried to call this using `connect` in the MainWindow as follows.

C++
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtSerialPort/QSerialPort>
#include "tetraserial.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

  connect(tetraSerial::serialObject, SIGNAL(readyRead()),this,SLOT(serialRecived()));

}



I'm getting a runtime error and throws this in the console.

cannot connect <null>::readData() Mainwindow::serialRecived
Posted
Updated 22-Mar-19 8:41am

1 solution

A serial port can only be accessed by one thread at a time (open; close).

Each Window has its own thread; so they cannot "share the port".

You can share the "data" / concurrent queues; not the port.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900