Qt on android 藍牙開發(控制小車)


因為要做一個用藍牙控制小車的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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM