How to make QT automatically connect to correct COM Port
-
I am trying to make QT automatically connect to my ST32 MCU by serial. MCU is keep sending data for each second. So I thought I can read all the available COM Ports and when the line is not null, I will detect that COM Port is MCU. But All COM Ports are null. Here is related piece of code I am using in QT:
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QtSerialPort> #include <QDebug> QSerialPort *serial; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); serial = new QSerialPort(this); foreach(QSerialPortInfo port, QSerialPortInfo::availablePorts()) { serial->setPortName(port.portName()); serial->setBaudRate(QSerialPort::Baud115200); serial->setDataBits(QSerialPort::Data8); serial->setParity(QSerialPort::NoParity); serial->setStopBits(QSerialPort::OneStop); serial->setFlowControl(QSerialPort::NoFlowControl); serial->open(QIODevice::ReadOnly); if(!(serial->readLine().isNull())) { qDebug()<<port.portName()<<"is opened"; } } }
I believe 1 second is not enough for QT to detect that. Maybe I should use timeout in QT. Any idea how can I solve this problem?
-
@GunkutA
point 1: you have no checks what so ever if the opening succeeds
point 2: There is no guarantee that your serialport instance already received data after opening, in fact it's near impossible.point 3: PLEASE use the asynchronous api of QSerialPort with readyRead & bytesWritten Signals etc.
-
@J-Hilk Thank you for your feedback. To make things more clear:
- I checked and all ports are connected successfully.
- My MCU is trying to send data for every 1 second, so maybe I should check it with a Signal and Slot. But in this case how I will test it with all COM Ports and find the correct one?
- I don't know what is "asynchronous api of QSerialPort with readyRead & bytesWritten Signals etc.". I am newbie to QT and C++...
-
@GunkutA said in How to make QT automatically connect to correct COM Port:
I don't know what is "asynchronous api of QSerialPort with readyRead & bytesWritten Signals etc."
Then please read documentation:
https://doc.qt.io/qt-5/qserialport.html
https://doc.qt.io/qt-5/qiodevice.html#readyRead
https://doc.qt.io/qt-5/qiodevice.html#bytesWrittenQt is an asynchronous framework and should be used as such.