Qt5自带串口初步用一下感觉还不错。
调试记录
.pro文件增加
QT += serialport
.h文件增加
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
private slots: void my_readuart();//串口接收数据槽函数
private:
QSerialPort *my_serialport;
.cpp文件
构造函数内
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { QSerialPort serial; serial.setPort(info); if (serial.open(QIODevice::ReadWrite)) { ui->comboBox->addItem(info.portName()); ui->textEdit->append(tr("检测到端口列表:")); ui->textEdit->append(info.portName()); ui->textEdit->append(info.description()); ui->textEdit->append(info.manufacturer()); serial.close(); } } my_serialport= new QSerialPort(); ui->pushButton_3->setEnabled(false); ui->comboBox_2->setCurrentIndex(1);//默认9600
开启串口按钮槽函数
void MainWindow::on_pushButton_clicked() { // my_serialport= new QSerialPort(); my_serialport->setPortName(ui->comboBox->currentText()); my_serialport->open(QIODevice::ReadWrite); my_serialport->setBaudRate(ui->comboBox_2->currentText().toInt()); my_serialport->setDataBits(QSerialPort::Data8); my_serialport->setParity(QSerialPort::NoParity); my_serialport->setStopBits(QSerialPort::OneStop); my_serialport->setFlowControl(QSerialPort::NoFlowControl); connect(my_serialport,SIGNAL(readyRead()),this,SLOT(my_readuart())); ui->pushButton->setEnabled(false);//禁止打开串口按钮 ui->pushButton_3->setEnabled(true);//允许关闭串口按钮 }
读串口槽函数
void MainWindow::my_readuart() { QByteArray requestData; requestData = my_serialport->readAll(); if(requestData!= NULL) { ui->textEdit->append(tr(requestData)); } requestData.clear(); }
发送数据槽函数
void MainWindow::on_pushButton_2_clicked() { my_serialport->write(ui->lineEdit->text().toLatin1()); }
关闭串口槽函数
void MainWindow::on_pushButton_3_clicked() { my_serialport->clear(); ui->pushButton->setEnabled(true); ui->pushButton_3->setEnabled(false); // my_serialport->deleteLater(); }
测试时使用9600波特率,数据接收反映很迅速,不需要Qt4中要检测接收缓冲区是否有剩余数据的问题。
时间: 2024-10-07 15:51:15