1. 介绍
Qt对串口通信提供了专用类QSerialPort,须要在pro文件增长:QT += serialport,其继承自QIODevicehtml
相关类还有QSerialPortInfo 提供当前设备串口信息app
2. QSerialPortInfo
QSerialPortInfo::availablePorts();函数
能够获取当前设备的全部串口信息,提供了如下操做函数,可得到对应的信息类型。ui
- 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为编号,此号通常不相同可用于串口设备识别。spa
3. QSerialPort
参考类帮助文档htm
相关串口配置函数:继承
- 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可开启串口ip
阻塞数据读写:文档
- virtual bool open(OpenMode mode)
- virtual bool waitForBytesWritten(int msecs = 30000)
- virtual bool waitForReadyRead(int msecs = 30000)
同时能够利用QIODevice类的readyRead信号,connect之后可在收到信息后在槽中响应,利用get
- qint64 read(char *data, qint64 maxSize)
- QByteArray read(qint64 maxSize)
- QByteArray readAll()
读取内容。
串口可能在发送一串字符时每个字符收到均有一次readyRead响应,此时须要自行判断终止符。