Qt5 串口通信 发送接收 源码例程
例程下载源码:
源码下载
下面介绍源码:
1. 添加到IntSertest.pro
QT += serialport;
如图所示:
2. MainWindow函数中添加:initSeialPort();
如图:
3.在析构函数中添加:
serial.close();
如图:
3. 在mainwindow.h中 按照图示添加:
(1)
#include <QSerialPort>
#include <QSerialPortInfo>
(2)
private:
QSerialPort serial;
void initSeialPort();
private slots:
void serialRead();
void on_comboBox_currentIndexChanged(const QString &arg1);
void on_pushButton_clicked();
void MainWindow::initSeialPort()
{
connect(&serial,SIGNAL(readyRead()),this,SLOT(serialRead())); //连接槽
//get name for choose
QList<QSerialPortInfo> infos = QSerialPortInfo::availablePorts();
if(infos.isEmpty())
{
ui->comboBox->addItem("无效");
return;
}
ui->comboBox->addItem("串口");
foreach (QSerialPortInfo info, infos) {
ui->comboBox->addItem(info.portName());
}
}
void MainWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
QSerialPortInfo info;
QList<QSerialPortInfo> infos = QSerialPortInfo::availablePorts();
int i = 0;
foreach (info, infos) {
if(info.portName() == arg1) break;
i++;
}
if(i != infos.size ()){//can find
ui->label->setText("[已开启]");
serial.close();
serial.setPort(info);
serial.open(QIODevice::ReadWrite); //读写打开
}
else
{
serial.close();
ui->label->setText("[出错]");
}
}
void MainWindow::serialRead()
{
ui->textEdit_2->append(serial.readAll());
}
void MainWindow::on_pushButton_clicked()
{
if(ui->lineEdit->text().isEmpty())
return;
serial.write(ui->lineEdit->text().toLatin1());
}
例程下载源码: