Qt操作串口的两个类便是QSerialPort和QSerialPortInfo
从类名可以知道QSerialPortInfo是用来获取串口信息的类,那么QSerialPort便是直接操作串口的类。
QSerialPortInfo
[static] QList<QSerialPortInfo> QSerialPortInfo::availablePorts()
函数功能:Returns a list of available serial ports on the system.
利用此函数显示计算机串口连接情况
QList<QSerialPortInfo> m_list = QSerialPortInfo::availablePorts();
for(int i = 0;i<m_list.count();i++)
{
qDebug() << "Name : " << m_list.at(i).portName();
qDebug() << "Description : " << m_list.at(i).description();
qDebug() << "Manufacturer: " << m_list.at(i).manufacturer();
qDebug() << "Serial Number: " << m_list.at(i).serialNumber();
qDebug() << "System Location: " << m_list.at(i).systemLocation();
}
还可以使用foreach
foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
{
qDebug() << "Name : " << info.portName();
qDebug() << "Description : " << info.description();
qDebug() << "Manufacturer: " << info.manufacturer();
qDebug() << "Serial Number: " << info.serialNumber();
qDebug() << "System Location: " << info.systemLocation();
}
QSerialPort
下面有几个方法比较常用
- bool setBaudRate(qint32 baudRate, Directions directions = AllDirections)
- bool setDataBits(DataBits dataBits)
- bool setFlowControl(FlowControl flowControl)
- bool setStopBits(StopBits stopBits)
- bool setParity(Parity parity)
- void QSerialPort::setPortName(const QString &name)
简单用上述方法写了一个小demo,功能是接收单片机发送过来的数据
serialport.h
#ifndef SERIALPORT_H
#define SERIALPORT_H
#include <QSerialPort>
#include <QSerialPortInfo>
class SerialPort : public QSerialPort
{
Q_OBJECT
public:
SerialPort();
bool openPort(QString);
void writeMsg(QString);
private slots:
void slot_DataRec();
};
#endif // SERIALPORT_H
serialport.cpp
#include "serialport.h"
#include <qDebug>
SerialPort::SerialPort()
{
this->setBaudRate(QSerialPort::Baud9600,QSerialPort::AllDirections);
this->setDataBits(QSerialPort::Data8);
this->setFlowControl(QSerialPort::NoFlowControl);
this->setStopBits(QSerialPort::OneStop);
this->setParity(QSerialPort::NoParity);
connect(this,SIGNAL(readyRead()),this,SLOT(slot_DataRec()));
}
bool SerialPort::openPort(QString port)
{
this->setPortName(port);
this->close();
if(this->open(QIODevice::ReadWrite))
return true;
else
return false;
}
void SerialPort::slot_DataRec()
{
QByteArray temp = this->read(1);
qDebug()<<temp;
}
void SerialPort::writeMsg(QString msg)
{
this->write(msg.toLatin1());
}
调用openPort函数便可以打开指定串口,接收到数据。
调用writeMsg函数可以向已经打开的串口发送数据。