Home > Enterprise >  QTserialport connection
QTserialport connection

Time:02-04

Im trying to use QTserialport to connect to a port via uart I get QIODevice::read (QSerialPort): device not open this but device is connect as i tested with other applications and with Qserialportinfo I was able to detect the serial port but not connect to it and read from it which part am i doing wrong ??

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>


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

    ui->setupUi(this);
    m.setBaudRate(QSerialPort::Baud115200);
    m.setDataBits(QSerialPort::Data8);
    m.setPortName("COM2");
    m.setFlowControl(QSerialPort::NoFlowControl);
    m.setParity(QSerialPort::NoParity);
    m.setStopBits(QSerialPort::OneStop);
    m.setReadBufferSize(1000);
    qDebug()<<m.portName();
  while(1){
    qDebug()<<m.readAll();
  }
}

MainWindow::~MainWindow()
{
    delete ui;
}

mainwindow.h


#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QSerialPort>

#include <QMainWindow>
#include <QSerialPortInfo>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QSerialPort m;
    QSerialPortInfo info;

};
#endif // MAINWINDOW_H


ps. I tried to use //./ & \.\ & ////.// & \\.\ before the port but it didnt worked

CodePudding user response:

I believe you have to open the port before reading from it. Try something like this:

   if (m.open(QIODevice::ReadOnly)){

       while (1){
           if (m.waitForReadyRead(1000)){
               qDebug() << m.readAll();
           }
       }
    }

CodePudding user response:

after adding m.open() worked perfectly

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>


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

    ui->setupUi(this);
    m.setBaudRate(QSerialPort::Baud115200);
    m.setDataBits(QSerialPort::Data8);
    m.setPortName("COM2");
    m.setFlowControl(QSerialPort::NoFlowControl);
    m.setParity(QSerialPort::NoParity);
    m.setStopBits(QSerialPort::OneStop);
    m.setReadBufferSize(1000);
    m.open(QIODevice::ReadOnly); //after adding this worked perfectly
    qDebug()<<m.portName();
  while(1){
    qDebug()<<m.readAll();
  }
}

MainWindow::~MainWindow()
{
    delete ui;
}
  • Related