SerialPort QT c++数据传感器



我正在编写一个程序,通过SerialPort从IMU传感器收集数据

后者的软件接收到的IMU数据为十六进制

所以我想在第一次用十六进制提取它们

您可以在附件中找到我的程序,问题是我在每次接收数据时接收到0。

static const int FRAME_SIZE = 68;
Imu::Imu() :
moving(false)
{
serialPort = new QSerialPort("COM3",this);
if (!serialPort->open( QIODevice::ReadOnly))
{
log_warning("imu","failed to open device file "%s", IMU measures will be unavailable",qPrintable(serialPort->portName()));
return;
}
if (!serialPort->setBaudRate(115200))
log_error("imu","failed to set baudrate, error no %d",serialPort->error());
serialPort->setDataBits(QSerialPort::Data8);
serialPort->setParity(QSerialPort::NoParity);
serialPort->setStopBits(QSerialPort::OneStop); // One Stop bit
serialPort->setFlowControl(QSerialPort::NoFlowControl);
pollingTimer = new QTimer(this);
QObject::connect(pollingTimer, SIGNAL(timeout()), this, SLOT(pollSerialPort()));
pollingTimer->start(10);
}
Imu::~Imu()
{
serialPort->close();
}
void Imu::pollSerialPort()
{
static const unsigned char START_BYTES[2] = {0x55,0xAA};
static const QByteArray START_WORD((char*)START_BYTES,2);
static QTime startTime = QTime::currentTime();
static QByteArray data;
data.append(serialPort->readAll());
qDebug() << data.count() << data.toHex();

Imu类中定义两个插槽,一个用于读取数据,另一个用于处理错误情况,然后像这样将它们连接到QSerialPorterrorOccurredreadyRead信号上。

serialPort = new QSerialPort("COM3",this);
connect(serialPort, &QSerialPort::errorOccurred, this, &Imu::handleError);
connect(serialPort, &QSerialPort::readyRead, this, &Imu::readData);

当数据到达串口时,Qt将自动调用readData插槽。在readData中,你可以得到这样的所有数据

void Imu::readData() {
const QByteArray data = serialPort->readAll();
qDebug() << data.count() << data.toHex();
}

handleError函数中,可以检查不同的错误情况:

void Imu::handleError(QSerialPort::SerialPortError error)
{
if (error == QSerialPort::ResourceError) {
// handle error
}
}

注:不要使用老式的信号/槽连接,使用新型的。下面的链接提供了很好的解释。

https://wiki.qt.io/New_Signal_Slot_Syntax

谢谢你的回答,

我readyread,然而这一次,我没有数据接收。甚至不是我开始时的0

有必要这样声明连接吗?和/或在file.h .

中添加函数QByteArray是否适合读取serialport,因为它返回十六进制的数据

Thanks a lot

再次感谢您的回复。

QObject::connect(serialPort, &QSerialPort::errorOccurred, this, &Imu::handleError);
QObject::connect(serialPort, &QSerialPort::readyRead, this, &Imu::pollSerialPort);

}
Imu::~Imu()
{
serialPort->close();
}
void Imu::handleError(QSerialPort::SerialPortError error)
{
if (error == QSerialPort::ResourceError) {
// qDebug()<<"handleerror" <<;
}
}

void Imu::pollSerialPort()
{
static const unsigned char START_BYTES[2] = {0x55,0xAA};
static const QByteArray START_WORD((char*)START_BYTES,2);
static QTime startTime = QTime::currentTime();
if (!pollingTimer->isActive()){
pollingTimer->start(10);
}
static QByteArray data;
data.append(serialPort->readAll());
qDebug() << data.count() << data.toHex();