【发布时间】:2020-09-13 06:13:07
【问题描述】:
我正在努力解决这个问题。但无法弄清楚问题是什么! 在Qt,C++中我尝试实现串口读写。它只能通过串口发送数据,但不能从另一端接收。我在谷歌和 StackOverFlow 上搜索但无法解决。 我安装了虚拟 com 端口对 COM1COM2
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSerialPort>
#include <QDebug>
//QSerialPort *serial;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
serial= new QSerialPort(this);
serial->setPortName("COM1");
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
//serial->clearError();
//serial->setDataTerminalReady(false);
//serial->clear();
// qDebug() << "serial->open(QIODevice::ReadWrite)";
//serial->open(QIODevice::ReadWrite);
if (serial->open(QIODevice::ReadWrite))
{
qDebug() << "Com port opened";
// serial->setDataTerminalReady(false);
serial->write("Hello");
}
else
{
qDebug() << "Not opened";
}
ui->label->setText("Waiting..");
connect(serial,SIGNAL(readyRead()),this,SLOT(serialReceived()));
connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this,SLOT(handleError(QSerialPort::SerialPortError)));
}
MainWindow::~MainWindow()
{
delete ui;
serial->close();
}
void MainWindow::serialReceived(){
//QString received = this->Read();
//qDebug() << "received data:" << received;
QByteArray ba;
ba=serial->readAll();
ui->label->setText("Waiting..");
ui->label->setText(serial->readAll());
qDebug()<<ba;
qDebug() << "bytes available:" << serial->bytesAvailable();
}
void MainWindow::handleError(QSerialPort::SerialPortError error)
{
qDebug()<<"Error:"<<error;//I added this line
if(error==QSerialPort::ResourceError)
{
qDebug()<<"serial->errorString())";
//closeSerialPort();
}
}
COM1 在 Qt 代码中分配,COM2 在串行监视器中打开。
为了测试,我编写了运行良好的 PythonQT 代码,但我的要求是 c++
【问题讨论】:
-
您知道您在
MainWindow::serialReceived中调用了两次serial->readAll()?我怀疑只有第一个会包含有意义的数据。 -
无关:请停止使用 Qt4 SIGNAL/SLOT 语法。 new syntax 更安全、更容易输入。
-
@Botje 是的,我是故意这样做的。第一个没有提供任何数据。
-
@Botje 我将更新到新的 SIGNAL SLOT 语法。但这也应该有效!