【问题标题】:QT C++ app crashing when send data with serial port使用串口发送数据时 QT C++ 应用程序崩溃
【发布时间】:2022-07-19 01:31:28
【问题描述】:

我只是想通过串口发送数据,但我收到段错误错误。

当我点击void productDetail::on_detailSaveBtn_clicked()) 时出现错误

下级停止了,因为它收到了来自操作系统的信号。

Signal name : SIGSEGV
Signal meaning : Segmentation fault

Debug 在这一行显示 arron

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

有人可以帮我解决一下吗?

这是我的代码。

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());


 }

【问题讨论】:

  • serial1 在发布的代码中看起来没有初始化。如果您认为已初始化,请发帖Minimal, Reproducible Example
  • 如果你没有 @MikeCAT 找到你的错误,请显示你有 serial1=new QSerialPort(this); 的代码。
  • 我没有`serial1=new QSerialPort(this);`我应该在哪里写这个? @drescherjm
  • 在你的构造函数中productDetail::productDetail(QWidget *parent)
  • 我应用了您所说的更改。该程序可以正常工作而不会崩溃。但是当我按下按钮时,串口并没有打开。一切似乎都是正确的。 @drescherjm

标签: c++ qt serial-port


【解决方案1】:

如果您通过 cgdb、lldb 或任何 IDE 中的任何调试器运行代码,它会告诉您崩溃的位置。根据您的进一步澄清,您似乎正在尝试在尚未构造的 QSerialPort 实例上调用方法。

您需要按照我在 QtSerialPort 中编写的示例创建串行端口实例。

另外,如果你让它成为你的类的成员,你实际上不需要在堆上构造和分配这个实例。您也可以在堆栈上分配它,以避免进一步的复杂性。

换句话说,只需从此处删除星号,然后删除 -&gt; 指针成员引用。

QSerialPort serial1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多