10

QT串口通信

 3 years ago
source link: http://www.cnblogs.com/zhwBlog/p/13973475.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

QT 中串口通信需要使用到 QSerialPort 类,需要在 pro 文件中添加 Qt += serialport 才能够正常使用

头文件中添加 #include <QSerialPort>

写在前面

相关内容仅供参考,如有雷同,不胜荣幸,以下内容仅为自己工作中遇到的,很片面与简单,许多内容都不全,欢迎批评指正交流,相互学习成长,在此感谢。

一般需要使用到 QSerialPort 类的函数:

void setPortName() ; ///< 设置端口号

bool setBaudRate ();///< 设置波特率

bool setDataBits() ; ///< 设置数据位

bool setStopBits(); ///< 设置停止位

bool setParity(); ///< 设置校验位

bool setFlowControl (); ///< 设置流控制

相关函数参数说明:

波特率函数参数类型 QSerialPort::BaudRate

数据位函数参数类型 QSerialPort::DataBits

停止位函数参数类型 QSerialPort::StopBits

校验位函数参数类型 QSerialPort::Parity

流控制函数参数类型 QSerialPort::FlowControl

(相关内容在 Qt 头文件中和帮助文档中都有描述,此处不多做解释.)

获取其他信息方式

获取当前机器可用串口

QList<QSerialPortInfo> portInfos = QSerialPortInfo::availblePorts ();

打开串口

设置打开串口需要设置的内容

m_serialPort->setPortName();

m_serialPort->setBaudRate();

m_serialPort->setDataBits();

m_serialPort->setStopBits();

m_serialPort->setParity();

m_serialPort->setFlowControl();

if( !m_serialPort->open(QIODevice::ReadWrite))

return false;

读取串口内容

                  QByteArray n_byteArray = m_serialPort->readAll();

/// 解析读取得内容

关闭串口

m_serialPort->flush();

m_serialPort->close();

其他

  如果需要实时得从串口读取内容,则应该使用 QSerialPort::readyRead().

通过链接当前信号,即可实时的从串口中获取信息.

例: connect(m_serialPort,  &QSerialPort::readyRead,  this,  &GetSerialPortInfo::slotSerialPortReadyRead);


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK