简体   繁体   中英

Problem with writing on serial port in QT

I want to write to a serial port. By using hercules, I have opened the port "COM6" and when I run the program, I can see the text "ok" in hercules window. But when I put the line "serial->write("ok");"inside a while loop, even my mainwindow isn't poped up. I would appreciate if someone could help me fix this problem

my code:

widget.h:

 #ifndef WIDGET_H
 #define WIDGET_H

 #include <QWidget>
 #include <QtSerialPort/QSerialPort>

 namespace Ui {
 class Widget;
   }

class Widget : public QWidget
 {
   Q_OBJECT

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

 QSerialPort *serial;

private slots:
   void on_pushButton_clicked();


private:
    Ui::Widget *ui;
};

 #endif // WIDGET_H

widget.cpp:

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QtSerialPort/QSerialPort>
#include <QSerialPortInfo>

Widget::Widget(QWidget *parent) :
      QWidget(parent),
      ui(new Ui::Widget)
  {
        ui->setupUi(this);

    serial = new QSerialPort(this);

    serial->setPortName("COM1");

    for(const auto &serialPortInfo : QSerialPortInfo::availablePorts())
    {
            qDebug() << "find serial port: " << serialPortInfo.portName() ;
    }

    serial->open(QIODevice::ReadWrite);

    if(serial->isOpen())
    {
        serial->setBaudRate(QSerialPort::Baud9600);
        serial->setDataBits(QSerialPort::Data8);
        serial->setParity(QSerialPort::NoParity);
        serial->setStopBits(QSerialPort::OneStop);
        serial->setFlowControl(QSerialPort::NoFlowControl);

        while(1)
          {
             serial->write("ok");
             
          }
    }

    else
    {
      qDebug() << "can't open the port";
    }

}

Widget::~Widget()
{
   delete ui;
  serial->close();
 }

void Widget::on_pushButton_clicked()
{
    qDebug() << "salam";
}

main.cpp:

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
   Widget w;
    w.show();

  return a.exec();
}

Only when this constructor is done, the UI can show up, but it blocked by the endless while loop.You need to move the while loop to another place, a manual trigger function or a thread will be OK.

Move your sending function to your on_pushButton_clicked slot to send your message when you click on your button.

void Widget::on_pushButton_clicked()
{
    qDebug() << "salam";
    serial->write("ok");
}

Also if you want to send something in a loop you can define a QTimer and send you message when QTimer triggered.

You can use this answer to implement QTimer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM