蓝牙的连接和初始化
工程文件加入蓝牙:
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)));
//蓝牙设备扫描完毕后,便会释放一个finished信号
connect(blt->discoveryAgent,SIGNAL(finished()),this,SLOT(scanFinshed()));
//通过按键调用,扫描蓝牙
void Dialog::on_BtnScan_clicked()
{
blt->bltScan();
}
//每扫描到一个蓝牙设备后便会跳转到此槽函数
void Dialog::bltDevDiscover(const QBluetoothDeviceInfo &info)
{
QString label = QString("%1 %2").arg(info.address().toString()).arg(info.name());
//listWidget 是我界面中的控件List Widget的对象名
QList<QListWidgetItem *> items = ui->listWidget->findItems(label, Qt::MatchExactly);
if (items.empty() && !(info.name().isEmpty())) {
QListWidgetItem *item = new QListWidgetItem(label);
QBluetoothLocalDevice::Pairing pairingStatus = blt->localDevice->pairingStatus(info.address());
if (pairingStatus == QBluetoothLocalDevice::Paired || pairingStatus == QBluetoothLocalDevice::AuthorizedPaired )
item->setForeground(QColor(Qt::blue));
else
item->setForeground(QColor(Qt::black));
//将每个扫描到的蓝牙设备显示出来。
ui->listWidget->addItem(item);
}
}
//蓝牙设备扫描完毕后便会跳转到此槽函数
void Dialog::scanFinshed()
{
QMessageBox::warning(this,tr("蓝牙扫描"),tr("扫描完成!"));//添加提示
}
//开始连接选中的蓝牙设备
static const QLatin1String serviceUuid("00001101-0000-1000-8000-00805F9B34FB");
void Dialog::on_BtnLink_clicked()
{
//这里的selTtem是ListWidget中你选中的蓝牙
if (selItem != NULL)
{
QString text = selItem->text();
int index = text.indexOf(' ');
if(index == -1){
return;
}
QBluetoothAddress Address(text.left(index));
// QString name(text.mid(index + 1));
// QString temp = QString("%1").arg(Address.toString());
// ui->editRecv->append(QStringLiteral("你链接的蓝牙地址是:")+temp);
// ui->editRecv->append(QStringLiteral("你链接的蓝牙名字:")+name);
blt->socket->connectToService(Address, QBluetoothUuid(serviceUuid) ,QIODevice::ReadWrite);
connect(blt->socket,SIGNAL(connected()),this,SLOT(bltConnected()));
connect(blt->socket, QOverload<QBluetoothSocket::SocketError>::of(&QBluetoothSocket::error),
[=](){
qDebug()<<QString("Connect error:")+blt->socket->errorString();
});
}
}
//连接成功
void Dialog::bltConnected()
{
// ui->editRecv->append(QStringLiteral("成功链接!"));
connect(blt->socket,SIGNAL(readyRead()),this,SLOT(bltReadMsg()));
blt_connected = true;
ui->tabWidget->setCurrentIndex(1);
}
//读取接收的数据
void Dialog::bltReadMsg()
{
QByteArray get = blt->socket->readAll();
QString strRecv = QString(get);
//接收数据处理
//注意:接收到的数据是片段的,需要自己根据数据格式拼接起来
}
//按键发送数据
void Dialog::on_BtnSend_clicked()
{
QMessageBox *msg_box= new QMessageBox(QMessageBox::NoIcon,QStringLiteral("注意"),QStringLiteral("请链接BLT"));
if(blt_connected == true)
{
QString data = "蓝牙真好玩";
QByteArray tba;
// tba = HexStringToByteArray(data); 十六进制发送
tba = data.toLatin1(); //字符发送
blt->socket->write(tba);
}
else
msg_box->exec();
}
//字符串转16进制数据
QByteArray Dialog::HexStringToByteArray(QString HexString)
{
bool ok;
QByteArray ret;
HexString = HexString.trimmed();
HexString = HexString.simplified();
QStringList sl = HexString.split(" ");
foreach (QString s, sl) {
if(!s.isEmpty())
{
uint32_t td = s.toUInt(&ok, 16);
int pos = ret.size();
if (ok)
{
do {
ret.insert(pos, td & 0xFF);
// ret.append(td & 0xFF);
td >>= 8;
}while(td > 0);
}
}
}
qDebug()<<ret;
return ret;
}
曲线绘制
1、QCustomPlot介绍
QCustomPlot是一个小型的Qt画图标类,支持绘制静态曲线、动态曲线、多重坐标曲线,柱状图,蜡烛图等。只需要在项目中加入头文件qcustomplot.h和qcustomplot.cpp文件,然后使一个widget提升为QCustomPlot类,即可使用。
QCustomPlot官网:
官网 例子与说明:
QCustomPlot下载地址:
这里我提供下网盘下载:
链接:https://pan.baidu.com/s/1lf7mXOb3q0LaggOT6fLQkg
提取码:rnbk
1
QCustomPlot帮助文件
QCustomPlot源码包中,有QCustomPlot帮助文件,将其添加进Qt帮助文件,如图,点击添加按钮,在下载的QCustomPlot源码包中找到qch为后缀的文件进行添加。
2、简单例子详解:
建立Qt工程,将下载的QCustomPlot源码中的qcustomplot.h和qcustomplot.cpp文件复制到项目所在文件夹,如图
.pro文件中加入支持
QT += core gui printsupport
在UI界面拖入一个widget,如图
UI界面右键widget,点击提升为,选择全局包含,如图
编写代码:
Mainwindow.h文件
#include "qcustomplot.h"
Mainwindow.c文件
int mCount = 1;
uint8_t MAX_point_num = 100;
void Dialog::GraphInit()
{
加速度曲线///
//设定右上角图形标注可见
ui->widget->legend->setVisible(true);
//设定右上角图形标注的字体
ui->widget->legend->setFont(QFont("Helvetica", 9));
//添加图形
ui->widget->addGraph();
//设置画笔
ui->widget->graph(0)->setPen(QPen(Qt::red));
//设置右上角图形标注名称
ui->widget->graph(0)->setName("ax");
ui->widget->addGraph();
ui->widget->graph(1)->setPen(QPen(Qt::blue));
ui->widget->graph(1)->setName("ay");
/*画静态曲线
QVector<double> temp(20);
QVector<double> temp1(20);
//图形为y = 100*x;
for(int i=0;i<20;i++)
{
temp[i] = i;
temp1[i] = 10*i+10;
}
//传入数据
ui->widget->graph(1)->setData(temp,temp1);
*/
ui->widget->addGraph();
ui->widget->graph(2)->setPen(QPen(Qt::green));
ui->widget->graph(2)->setName("az");
//设置X轴文字标注
ui->widget->xAxis->setLabel("点数");
//设置Y轴文字标注
ui->widget->yAxis->setLabel("加速度");
//设置X轴坐标范围
ui->widget->xAxis->setRange(0,MAX_point_num);
//设置Y轴坐标范围
ui->widget->yAxis->setRange(-20000,20000);
//在坐标轴右侧和上方画线,和X/Y轴一起形成一个矩形
ui->widget->axisRect()->setupFullAxesBox();
}
void Dialog::updataAccData(uint8_t graphIndex, int mData)
{
ui->widget->graph(graphIndex)->addData(mCount-1, mData);
if(mCount >= MAX_point_num)
{
ui->widget->xAxis->setRange(mCount-MAX_point_num, MAX_point_num, Qt::AlignLeft);
}
ui->widget->replot();
}
//数据来临时调用即可,ax,zy,az是我的数据
updataAccData(0, ax);
updataAccData(1, ay);
updataAccData(2, az);
mCount++; //注意别忘了增加数据点数
效果如图,会自动滚动:
曲线绘制部分参考原文:https://blog.csdn.net/qq_40194498/article/details/79666903