文章目录
Qt QSerialPort
串口编程
Qt 框架的Qt Serial Port 模块提供了访问串口的基本功能,包括串口通信参数配置和数据读写,使用 Qt Serial Port 模块就可以很方便地编写具有串口通信功能的应用程序。
Qt Serial Port模块简述
Qt Serial Port 模块用于串口通信编程,要在一个项目中使用 Qt Serial Port 模块,需要在项目配置文件中加入一行语句:QT += serialport
Qt Serial Port 模块中只包含有两个类:QSerialPortInfo
和 QSerialPort
。
1.QSerialPortInfo类
QSerialPortInfo
类有两个静态函数可以用于获取系统中可用的串口列表,以及系统支持的串口通信波特率列表,这两个静态函数定义如下:
QList<QSerialPortInfo> QSerialPortInfo::availablePorts()
//获取系统中的串口列表
QList<qint32> QSerialPortInfo::standardBaudRates()
//获取目标平台支持的可用标准波特率列表
静态函数 availablePorts()
返回一个 QSerialPortInfo
对象的列表,列表中的每个 QSerialPortInfo
对象代表一个串行端口,可以查询端口名称、系统位置、描述、制造商以及一些其他的硬件信息。QSerialPortInfo
类也可以用作QSerialPort
类的setPort()
方法的输入参数。
1.1示例用法
示例代码枚举所有可用的串行端口,并将其参数打印到控制台:
const auto serialPortInfos = QSerialPortInfo::availablePorts();
for (const QSerialPortInfo &portInfo : serialPortInfos) {
qDebug() << "\n"
<< "Port:" << portInfo.portName() << "\n"
<< "Location:" << portInfo.systemLocation() << "\n"
<< "Description:" << portInfo.description() << "\n"
<< "Manufacturer:" << portInfo.manufacturer() << "\n"
<< "Serial number:" << portInfo.serialNumber() << "\n"
<&