Qt5 SerialPort下面代码的关键两个地方,就是读和写两个位置,因为串口是不稳定的,所以必须以这种方式来收发。

[cpp]view plaincopy

#include"stdafx.h"

#include"serialporttesttool.h"

SerialPortTestTool::SerialPortTestTool(QWidget*parent)

:QMainWindow(parent)

{

ui.setupUi(this);

sp=newQSerialPort("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();

deletesp;

}

voidSerialPortTestTool::on_lineEdit_returnPressed()

{

QByteArraycommand=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");

}

}

voidSerialPortTestTool::serialRead()

{

staticQByteArrayallData;

QByteArraydataTemp;

while(!sp->atEnd())

{

dataTemp=sp->readLine();

ui.textEdit->append(QString::fromLatin1(dataTemp));

}

}

voidSerialPortTestTool::on_pushButton_clicked()

{

QByteArraytemp=sp->readAll();

while(sp->waitForReadyRead(10))

{

temp+=sp->readAll();

}

ui.textEdit->append(QString::fromLatin1(temp));

}