Home > Enterprise >  QT C app crashing when send data with serial port
QT C app crashing when send data with serial port

Time:07-20

I am simply trying to send data via serial port, but I am getting segment fault error.

When I click void productDetail::on_detailSaveBtn_clicked()) I got thıs error

The inferior stopped because it received a signal from the operating system.

Signal name : SIGSEGV
Signal meaning : Segmentation fault

Debug shows arron on this line

 { return write(data.constData(), data.size()); }

Can someone help me please how can I solve it?

Here is my code.

productdetail.h


#ifndef PRODUCTDETAIL_H
#define PRODUCTDETAIL_H

#include <QDialog>
#include <QSerialPort>

namespace Ui {
class productDetail;
}

class productDetail : public QDialog
{
    Q_OBJECT

public:
    explicit productDetail(QWidget *parent = nullptr);
    ~productDetail();

private slots:
    void on_detailSaveBtn_clicked();

private:
    Ui::productDetail *ui;
    void connectSerial();
    QSerialPort *serial1;
};

#endif // PRODUCTDETAIL_H

productDetail.cpp

#include "productdetail.h"
#include "ui_productdetail.h"
#include <QDebug>
#include <QSerialPort>
#include <QMessageBox>
productDetail::productDetail(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::productDetail)
{
    ui->setupUi(this);
}

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


void productDetail::connectSerial(){




     //Set serial port name
     serial1->setPortName("COM3");
     //Open serial port
     serial1->open(QIODevice::WriteOnly);
     //set baud rate
     serial1->setBaudRate(9600);
     //Set the number of data bits
     serial1->setDataBits(QSerialPort::Data8);
      //Set parity
      serial1->setParity(QSerialPort::NoParity);
     //Set stop bit
     serial1->setStopBits(QSerialPort::OneStop);
     //set flow control
     serial1->setFlowControl(QSerialPort::NoFlowControl);



}
void productDetail::on_detailSaveBtn_clicked()
{


serial1->write(ui->productDesp->text().toLatin1());


 }

CodePudding user response:

If you run your code through cgdb, lldb, or any debugger in any IDEs, it will tell you where it is crashing. Based on your further clarification, it seems that you are trying to call a method on an instance of QSerialPort which has not been constructed yet.

You need to create the serial port instance as per the examples I authored in QtSerialPort.

Also, if you make it a member of your class, you do not really need to construct and allocate this instance on the heap. You could just as well allocate this on the stack avoiding further complexities.

In other words, just remove the star from here and then the -> pointer member references.

QSerialPort serial1;
  • Related