Solved can't open ther serialport
-
Hi everyone
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); 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(); }
-
@nanor
You (try to) open the port twice. Presumably the second open fails because it's already open from the first one? At least that's the first thing to fix. -
@JonB I closed hercules. the port isn't opened now by hercules. But I still can't open the port from QT
-
@JonB Sorry. Yes you are right. In my code, I have to write if(serial->isOpen()) instead of open. Now it works well. Thank you