Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Open serial port when clicked the button



  • Why my app crashed when i clicked the push button?
    I want to open a port when i clicked the button. Program is crash every time.

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QtSerialPort/QSerialPort>
    #include <QDebug>
    #include <QSerialPortInfo>
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        
        
    }
    MainWindow::~MainWindow()
    {
        delete ui;
        serial->close();
    }
    
    void MainWindow::on_ports_activated(const QString &arg1)
    {
    ui->ports->clear();
    const auto infos = QSerialPortInfo::availablePorts();
    for(const QSerialPortInfo &info : infos )
    {
        QString s = info.portName();
        ui->ports->addItem(s);
    }
    if (!ui->ports->count())
                ui->ports->addItem(tr("no com"));
    
    }
    
    void MainWindow::on_pushButton_clicked()
    {
        serial->setPortName("/dev/ttyS1");
        serial->setBaudRate(QSerialPort::Baud115200);
        serial->setDataBits(QSerialPort::Data8);
        serial->setParity(QSerialPort::NoParity);
        serial->setStopBits(QSerialPort::OneStop);
        serial->setFlowControl(QSerialPort::NoFlowControl);
        if (serial->open(QIODevice::ReadWrite)) {
              qDebug()<<"Serial Port Open ";
              serial->clear();
        }
        else
        {
              qDebug()<<"Serial  Port Not Open !!!!";
        }
    }
    

  • Lifetime Qt Champion

    C++ basics - where do you initialize your member serial ?



  • @Christian-Ehrlicher Oh yes i forgot it. I initialize it now. Thank you


  • Lifetime Qt Champion

    @suslucoder Then mark the topic as solved.