Qt5自带串口库,很不错,把源码贴出来和大家分享一下,本人使用的是CC2530单片机测试进行了数据的回显。
#include "serial.h"
#include "ui_serial.h"
#include <QtSerialPort/QtSerialPort>
#include<QThread>
serial::serial(QWidget *parent) :
QWidget(parent),
ui(new Ui::serial)
{
ui->setupUi(this);
bool success;
serialPort = new QSerialPort("COM7");
if(serialPort->open(QIODevice::ReadWrite)){
success = serialPort->setBaudRate(115200)&&
serialPort->setDataBits(QSerialPort::Data8)&&
serialPort->setParity(QSerialPort::NoParity)&&
serialPort->setStopBits(QSerialPort::OneStop)&&
serialPort->setFlowControl(QSerialPort::NoFlowControl);
}
qDebug()<<success;
connect(ui->sendButton,SIGNAL(clicked()),this,SLOT(sendMessageToSerialPort()));
}
serial::~serial()
{
delete ui;
delete serialPort;
}
void serial::sendMessageToSerialPort()
{
char* ch;
QByteArray ba = ui->sendText->toPlainText().toLatin1();
ch=ba.data();
qDebug()<<ch;
serialPort->write(ch);
serialPort->waitForBytesWritten(10);
serialPort->clear();
QByteArray out;
if(serialPort->waitForReadyRead(20))
{
out =serialPort->readAll();
}
serialPort->clear();
ui->receiveText->setPlainText(QString(out));
qDebug()<<"out:"<<out;
out.clear();
}
对于电脑的串口可以采用Qseriport中的静态函数QSerialPortInfo::availablePorts()获取当前有效的串口号,笔者建议采用线程的方法和串口进行通信。