Qt5 SerialPort下面代码的关键两个地方,就是读和写两个位置,因为串口是不稳定的,所以必须以这种方式来收发。
[cpp] view plain copy
#include "stdafx.h"
#include "serialporttesttool.h"
SerialPortTestTool::SerialPortTestTool(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
sp = new QSerialPort("com4",this);
if (sp->open(QIODevice::ReadWrite))
{
sp->setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections);
sp->setDataBits(QSerialPort::Data8);
sp->setStopBits(QSerialPort::OneStop);
sp->setParity(QSerialPort::NoParity);
sp->setFlowControl(QSerialPort::NoFlowControl);
//connect(sp,SIGNAL(readyRead()),this,SLOT(serialRead()));
}
}
SerialPortTestTool::~SerialPortTestTool()
{
sp->close();
delete sp;
}
void SerialPortTestTool::on_lineEdit_returnPressed()
{
QByteArray command = ui.lineEdit->text().trimmed().toLocal8Bit() + "\r\n";
sp->write(command,command.length());
ui.lineEdit->setText("");
if (sp->waitForBytesWritten(2000))
{
ui.textEdit->append("ok");
}
else
{
ui.textEdit->append("failed");
}
}
void SerialPortTestTool::serialRead()
{
static QByteArray allData;
QByteArray dataTemp;
while (!sp->atEnd())
{
dataTemp = sp->readLine();
ui.textEdit->append(QString::fromLatin1(dataTemp));
}
}
void SerialPortTestTool::on_pushButton_clicked()
{
QByteArray temp = sp->readAll();
while (sp->waitForReadyRead(10))
{
temp += sp->readAll();
}
ui.textEdit->append(QString::fromLatin1(temp));
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。