因为要做一个用蓝牙控制小车的app,就用着QT搞了下,网上关于QT蓝牙开发的资料比较少,我在这里记录下过程希望对看到了人有所帮助

首先在项目文件里添加

QT += bluetooth

这样就可以用QT关于蓝牙的一系列类了,接下来在添加头文件

#include <QtBluetooth/qbluetoothglobal.h>
#include <QtBluetooth/qbluetoothlocaldevice.h>
#include <qbluetoothaddress.h>
#include <qbluetoothdevicediscoveryagent.h>
#include <qbluetoothlocaldevice.h>
#include <qbluetoothsocket.h>

添加要用的私有成员变量

private:
    Ui::BLE *ui;
    QBluetoothDeviceDiscoveryAgent *discoveryAgent;
    QBluetoothLocalDevice *localDevice;
    QBluetoothSocket *socket;

构造函数

discoveryAgent = new QBluetoothDeviceDiscoveryAgent();
    localDevice = new QBluetoothLocalDevice();
    /* 给socket分配内存,限定套接字协议 */
    socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
    /* 判断蓝牙是否开启,若开启则不可被选中并扫描周围蓝牙设备 */
    if( localDevice->hostMode() == QBluetoothLocalDevice::HostPoweredOff )
    {
        ui->pushButton_openBLE->setEnabled(true);
        ui->pushButton_upDateBLE->setEnabled(false);
        /* 开始扫描蓝牙设备 */
        discoveryAgent->start();
    }
    else
    {
        ui->pushButton_openBLE->setEnabled(false);
        ui->pushButton_upDateBLE->setEnabled(true);
    }
    /* 发现设备时会触发deviceDiscovered信号,转到槽显示蓝牙设备 */
    connect(discoveryAgent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
            this, SLOT(addBlueToothDevicesToList(QBluetoothDeviceInfo)));
    connect(discoveryAgent, SIGNAL(finished()), this, SLOT(findFinish()));
    /* 双击listwidget的项目,触发连接蓝牙的槽 */
    connect(ui->listWidget, SIGNAL(itemActivated(QListWidgetItem*)),
            this, SLOT(connectBLE(QListWidgetItem*)));
    connect(socket, SIGNAL(connected()), this, SLOT(connectOK()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(connectNot()));

下面是各个槽函数实现

/* 打开蓝牙并查找蓝牙设备 */
void BLE::on_pushButton_openBLE_clicked()
{
    localDevice->powerOn();
    ui->pushButton_openBLE->setEnabled(false);
    ui->pushButton_upDateBLE->setEnabled(true);
    /* 开始扫描蓝牙设备 */
    discoveryAgent->start();
}
/* 刷新 重新查找蓝牙设备 */
void BLE::on_pushButton_upDateBLE_clicked()
{
    discoveryAgent->start();
    ui->pushButton_upDateBLE->setEnabled(false);
}
/* 返回控制页面 */
void BLE::on_pushButton_return_clicked()
{
    this->hide();
    Control *c = new Control();
    c->show();
}
/* 在ListWidget上显示查找到的蓝牙设备 */
void BLE::addBlueToothDevicesToList(const QBluetoothDeviceInfo &info)
{
    QString label = QString("%1 %2").arg(info.address().toString()).arg(info.name());

    QList<QListWidgetItem *> items = ui->listWidget->findItems(label, Qt::MatchExactly);

    if (items.empty()) {
        QListWidgetItem *item = new QListWidgetItem(label);
        QBluetoothLocalDevice::Pairing pairingStatus = localDevice->pairingStatus(info.address());
        /* 蓝牙状态pairingStatus,Pairing枚举类型 0:Unpaired没配对 1:Paired配对但没授权 2:AuthorizedPaired配对且授权 */
        if (pairingStatus == QBluetoothLocalDevice::Paired || pairingStatus == QBluetoothLocalDevice::AuthorizedPaired )
            item->setTextColor(QColor(Qt::green));
        else
            item->setTextColor(QColor(Qt::black));
        ui->listWidget->addItem(item);
    }
}
/* 刷新完成 */
void BLE::findFinish()
{
    ui->pushButton_upDateBLE->setEnabled(true);
}
/* 蓝牙连接 */
void BLE::connectBLE(QListWidgetItem *item)
{
    QString text = item->text();
    int index = text.indexOf(' ');
    if (index == -1)
        return;
    QBluetoothAddress address(text.left(index));
    QString name(text.mid(index + 1));
    QMessageBox::information(this,tr("Info"),tr("The device is connecting..."));
    socket->connectToService(address, QBluetoothUuid(serviceUuid) ,QIODevice::ReadWrite);
}
/* 连接成功 */
void BLE::connectOK()
{
    discoveryAgent->stop();  //停止搜索设备
    QMessageBox::information(this, tr("成功"), tr("连接成功!"));
}
/* 连接失败 */
void BLE::connectNot()
{
    QMessageBox::information(this, tr("错误"), tr("连接失败!"));
}

不要忘记设置蓝牙的uuid码

static const QLatin1String serviceUuid("00001101-0000-1000-8000-00805F9B34FB");

蓝牙的发送、读取数据和服务器客户端发送读取数据一样,发送数据用write() 读取数据先接收到readyRead()信号然后用readAll()读取

现在构造函数中添加信号和槽连接

connect(socket, SIGNAL(readyRead()), this, SLOT(readBluetoothDataEvent()));

槽函数

void BLE::readBluetoothDataEvent()
{

    QByteArray line = socket->readAll();
    QString strData = line.toHex();
    comStr.append(strData);
    qDebug() <<"rec data is: "<< comStr;
    qDebug() <<"The comStr length is: " << comStr.length();
    if(comStr.length() >= 30) {

        ui->textBrowser_info->append(comStr + "\n");
        comStr.clear();
    }

}

OK啦

下面附一个我的蓝牙控制小车的源码

链接:https://pan.baidu.com/s/15JjHSm-KQIsbN-zHOFW6IQ  密码:nxc0

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐