QextSerialPort是一个跨平台的第三方串口类,可以很方便地在QT中对串口读写操作。但是默认使用的读写方式是查询方式,一般都是在程序中使用定时器。如果需要快速响应串口读写,可以使用多线程方式。在qtcentre论坛上找到了一位作者贴出了自己的源码,在此转贴出来,方便大家。(原帖地址:http://www.qtcentre.org/threads/21063-QextSerialPort-with-QTimer-approch-for-reading?p=103325&highlight=#post103325)
程序是QT4直接可用的。如果是QTE2,相应做一些修改后也可以工作。
mythreadport.h
#ifndef MYSERIALPORT_H
#define MYSERIALPORT_H
#include
#include
#include
#include
#include
#include "qextserialport.h"
Q_DECLARE_METATYPE(BaudRateType);
Q_DECLARE_METATYPE(DataBitsType);
Q_DECLARE_METATYPE(ParityType);
Q_DECLARE_METATYPE(StopBitsType);
Q_DECLARE_METATYPE(FlowType);
class SendThread;
class ReceiveThread;
class MySerialPort : public QObject
{
Q_OBJECT
public:
MySerialPort();
MySerialPort(const QString &name, const BaudRateType baudRate,
const DataBitsType dataBits,
const ParityType parity, const StopBitsType stopBits, const
FlowType flowControl,
ulong seconds = 0, ulong milliseconds = 10);
~MySerialPort();
bool
open();
bool
open(const QString &name, const BaudRateType baudRate, const
DataBitsType dataBits,
const ParityType parity, const StopBitsType stopBits, const
FlowType flowControl,
ulong seconds = 0, ulong milliseconds = 10);
bool
isOpen() const;
void
close();
// Setter
and getter for the basic property of the QextSerialPort
void
setPortName(const QString &name);
QString
portName() const;
void
setBaudRate(const BaudRateType baudRate);
BaudRateType
baudRate() const;
void
setDataBits(const DataBitsType dataBits);
DataBitsType
dataBits() const;
void
setParity(const ParityType parity);
ParityType
parity() const;
void
setStopBits(StopBitsType stopBits);
StopBitsType
stopBits() const;
void
setFlowControl(const FlowType flowControl);
FlowType
flowControl() const;
void
setTimeout(const ulong seconds, const ulong milliseconds);
void
enableSending();
// enable the SerialPort to send data (init the thread)
void
disableSending();
// disable the SerialPort to send data (terminate the thread)
bool
isSendingEnable() const;
void
stopSending();
// stop the currently sending data operation (don't terminate the
thread)
uchar
sendData(const QByteArray &data); // send data to the
SerialPort (enqueue data to the sendThread queue)
// return
1
OK
// return
2
port not open
// return
3
sending operation disable
void
enableReceiving();
// enable the SerialPort to receive data (init the thread)
void
disableReceiving();
// disable the SerialPort to receive data (terminate the
thread)
bool
isReceivingEnable() const;
void
stopReceiving();
// stop the currently receiving data operation (don't terminate the
thread)
uchar
receiveData();