博客地址已更改,文章數量較多不便批量修改,若想訪問源文請到 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();
可以獲取當前設備的所有串口信息,提供了以下操作函數,可獲得對應的信息類型。
- QString description() const
- bool hasProductIdentifier() const
- bool hasVendorIdentifier() const
- bool isBusy() const
- bool isNull() const
- QString manufacturer() const
- QString portName() const
- quint16 productIdentifier() const
- QString serialNumber() const
- void swap(QSerialPortInfo &other)
- QString systemLocation() const
- quint16 vendorIdentifier() const
portName一般為“COMX”;Description為描述信息;serialNumber為編號,此號一般不相同可用於串口設備識別。
3. QSerialPort
參考類幫助文檔
相關串口配置函數:
- bool sendBreak(int duration = 0)
- bool setBaudRate(qint32 baudRate, Directions directions = AllDirections)
- bool setBreakEnabled(bool set = true)
- bool setDataBits(DataBits dataBits)
- bool setDataTerminalReady(bool set)
- bool setFlowControl(FlowControl flowControl)
- bool setParity(Parity parity)
- void setPort(const QSerialPortInfo &serialPortInfo)
- void setPortName(const QString &name)
- void setReadBufferSize(qint64 size)
- bool setRequestToSend(bool set)
- bool setStopBits(StopBits stopBits)
先配置完成后,調用open可開啟串口
阻塞數據讀寫:
- virtual bool open(OpenMode mode)
- virtual bool waitForBytesWritten(int msecs = 30000)
- virtual bool waitForReadyRead(int msecs = 30000)
同時可以利用QIODevice類的readyRead信號,connect以后可在收到信息后在槽中響應,利用
- qint64 read(char *data, qint64 maxSize)
- QByteArray read(qint64 maxSize)
- QByteArray readAll()
讀取內容。
串口可能在發送一串字符時每一個字符收到均有一次readyRead響應,此時需要自行判斷終止符。