QSerialPort-Qt串口通訊


博客地址已更改,文章數量較多不便批量修改,若想訪問源文請到 coologic博客 查閱,網址:www.coologic.cn

如本文記錄地址為 techieliang.com/A/B/C/ 請改為 www.coologic.cn/A/B/C/ 即可查閱

 

版權聲明:若無來源注明, Techie亮博客文章均為原創。 轉載請以鏈接形式標明本文標題和地址:
本文標題:QSerialPort-Qt串口通訊     本文地址: http://techieliang.com/2017/12/534/

1. 介紹

Qt對串口通訊提供了專用類QSerialPort,需要在pro文件增加:QT += serialport,其繼承自QIODevice

相關類還有QSerialPortInfo 提供當前設備串口信息

2. QSerialPortInfo

QSerialPortInfo::availablePorts();

可以獲取當前設備的所有串口信息,提供了以下操作函數,可獲得對應的信息類型。

  1. QString description() const
  2. bool hasProductIdentifier() const
  3. bool hasVendorIdentifier() const
  4. bool isBusy() const
  5. bool isNull() const
  6. QString manufacturer() const
  7. QString portName() const
  8. quint16 productIdentifier() const
  9. QString serialNumber() const
  10. void swap(QSerialPortInfo &other)
  11. QString systemLocation() const
  12. quint16 vendorIdentifier() const

portName一般為“COMX”;Description為描述信息;serialNumber為編號,此號一般不相同可用於串口設備識別。

3. QSerialPort

參考類幫助文檔

相關串口配置函數:

  1. bool sendBreak(int duration = 0)
  2. bool setBaudRate(qint32 baudRate, Directions directions = AllDirections)
  3. bool setBreakEnabled(bool set = true)
  4. bool setDataBits(DataBits dataBits)
  5. bool setDataTerminalReady(bool set)
  6. bool setFlowControl(FlowControl flowControl)
  7. bool setParity(Parity parity)
  8. void setPort(const QSerialPortInfo &serialPortInfo)
  9. void setPortName(const QString &name)
  10. void setReadBufferSize(qint64 size)
  11. bool setRequestToSend(bool set)
  12. bool setStopBits(StopBits stopBits)

先配置完成后,調用open可開啟串口

阻塞數據讀寫:

  1. virtual bool open(OpenMode mode)
  2. virtual bool waitForBytesWritten(int msecs = 30000)
  3. virtual bool waitForReadyRead(int msecs = 30000)

同時可以利用QIODevice類的readyRead信號,connect以后可在收到信息后在槽中響應,利用

  1. qint64 read(char *data, qint64 maxSize)
  2. QByteArray read(qint64 maxSize)
  3. QByteArray readAll()

讀取內容。

串口可能在發送一串字符時每一個字符收到均有一次readyRead響應,此時需要自行判斷終止符。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM