简体   繁体   中英

can't open the serial port from qt

I am working on a project where I have to write to an read from a serial port. I have written the following code, but I am getting the message "can't open the port" in my else statement. When I use hercules, I can open the "COM1" port. But I don't know why can't I open this port via my QT program.

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->open(QIODevice::ReadWrite))
    {
        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");
           qDebug() << " Reading " << serial->read(1);
           serial->flush();
       }



    }

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

You do open two times, I guess second one should be isOpen

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