蓝牙的连接和初始化
工程文件加入蓝牙:
QT += bluetooth
头文件:blt.h
#ifndef BLT_H
#define BLT_H
#include <QObject>
#include <QtBluetooth/qtbluetoothglobal.h>
#include <QtBluetooth/qbluetoothlocaldevice.h>
#include <QtBluetooth/qbluetoothsocket.h>
#include <QtBluetooth/qbluetoothservicediscoveryagent.h>
#include <QByteArray>
class BLT:public QObject
{
Q_OBJECT
public:
BLT(QObject *parent = nullptr);
QBluetoothDeviceDiscoveryAgent *discoveryAgent; //用来对周围蓝牙进行搜寻
QBluetoothLocalDevice *localDevice; //对本地设备进行操作,比如进行设备的打开,设备的关闭等等
QBluetoothSocket *socket; //就是用来进行蓝牙配对链接和数据传输的
public slots:
void bltScan();
};
#endif // BLT_H
C文件:
#include "blt.h"
BLT::BLT(QObject *parent) : QObject(parent)
{
discoveryAgent = new QBluetoothDeviceDiscoveryAgent();
localDevice = new QBluetoothLocalDevice();
socket =new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
}
void BLT::bltScan(){
//如果蓝牙没打开,则打开蓝牙
if(localDevice->hostMode() == QBluetoothLocalDevice::HostPoweredOff){
localDevice->powerOn();
}
//开始普通无限制搜寻模式
discoveryAgent->setInquiryType(QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry);
discoveryAgent->start();
}
调用步骤:
Mainwindow.h
#include <QDialog>
#include <QDebug>
#include <QListWidgetItem>
#include "blt.h"
//创建蓝牙对象
BLT *blt = new BLT();
bool blt_connected = false;
QListWidgetItem *selItem = NULL;
Mainwindow.c
//先连接信号和槽
//每扫到一个蓝牙设备后,便会释放一个deviceDiscovered信号
connect(blt->discoveryAgent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
this, SLOT(bltDevDiscover(QBluetoothDeviceInfo))

本文介绍了如何在Qt中使用蓝牙功能,包括设备搜索、连接和数据传输,并展示了如何利用QCustomPlot库绘制动态加速度曲线。首先,通过QT+=bluetooth添加蓝牙支持,然后实现设备扫描、连接和数据读写。接着,通过QCustomPlot库创建图表,设置坐标轴,动态更新加速度数据,实现曲线自动滚动。该教程适合Qt开发者学习蓝牙通信和实时数据可视化。
最低0.47元/天 解锁文章
152

被折叠的 条评论
为什么被折叠?



