Qt5 提供了两个类用于串口操作,分别是:QSerialPort和QSerialPortInfo。
最基本的操作示例代码如下:
1 #ifndef DIALOG_H 2 #define DIALOG_H 3 4 #include <QDialog> 5 6 #include <QDebug> 7 #include <QSerialPort> 8 #include <QSerialPortInfo> 9 10 namespace Ui { 11 class Dialog; 12 } 13 14 class Dialog : public QDialog 15 { 16 Q_OBJECT 17 18 public: 19 explicit Dialog(QWidget *parent = 0); 20 ~Dialog(); 21 22 QSerialPort m_Serail; 23 24 private slots: 25 void myRecvData(); 26 27 private: 28 Ui::Dialog *ui; 29 }; 30 31 #endif // DIALOG_H
1 #include "dialog.h" 2 #include "ui_dialog.h" 3 4 Dialog::Dialog(QWidget *parent) : 5 QDialog(parent), 6 ui(new Ui::Dialog) 7 { 8 ui->setupUi(this); 9 10 QSerialPortInfo serPortInfo; 11 foreach(const QSerialPortInfo &serInfo,QSerialPortInfo::availablePorts()) 12 { 13 qDebug() << "Name: " << serInfo.portName(); 14 qDebug() << "Description: " << serInfo.description(); 15 qDebug() << "Manufacturer: " << serInfo.manufacturer(); 16 qDebug() << "Serial Number: " << serInfo.serialNumber(); 17 qDebug() << "System Location: " << serInfo.systemLocation(); 18 serPortInfo = serInfo; 19 } 20 m_Serail.setPort(serPortInfo); 21 if(m_Serail.open(QIODevice::ReadWrite)) 22 { 23 qDebug() << "m_Serail.open(QIODevice::ReadWrite)"; 24 m_Serail.setBaudRate(QSerialPort::Baud115200); 25 m_Serail.setParity(QSerialPort::NoParity); 26 m_Serail.setDataBits(QSerialPort::Data8); 27 m_Serail.setStopBits(QSerialPort::OneStop); 28 m_Serail.setFlowControl(QSerialPort::NoFlowControl); 29 30 m_Serail.clearError(); 31 m_Serail.clear(); 32 connect(&m_Serail, SIGNAL(readyRead()), this, SLOT(myRecvData())); 33 } 34 } 35 36 Dialog::~Dialog() 37 { 38 delete ui; 39 } 40 41 void Dialog::myRecvData() 42 { 43 QByteArray arr = m_Serail.readAll(); 44 if(NULL != arr) 45 { 46 ui->logEdit->append(tr(arr)); 47 arr.clear(); 48 }49 }
时间: 2024-12-23 19:10:28