您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。