[[374870]] Achieving goals - Write your own Qt-based Android software to enable data communication between the mobile phone and the TB-02-kit module;
- The data sent by the Android software is forwarded to the serial port assistant through the TB-02-kit module;
- The data sent by the serial port assistant can be displayed in the Android software, thereby realizing two-way data communication of BLE.
Required tools and environment - TB-02-kit module
- Qt Creator 4.10.1
- Qt 5.13.1
- XCOM V2.0 Serial Port Assistant
- Android Phone
- My computer is Windows 10 64bit [version 10.0.19041.329]
Source code of this article Because this is the first time to share Qt code, in order to facilitate everyone's learning, a lot of comments have been added to the code, and everyone can learn more efficiently by referring to the code. Reply to the keyword "Android-BLE" in the backend to obtain the software and Qt project source code involved in this article. Specific implementation 1. To use the Qt Bluetooth module, you need to add a declaration to the project's .pro file. 2. Scan Devices Perform a scan for Bluetooth devices in the constructor, that is, as soon as the software starts. - Widget::Widget(QWidget *parent)
- : QWidget(parent)
- , ui(new Ui::Widget)
- {
- ui->setupUi(this);
-
- //Create a search service: https://doc.qt.io/qt-5/qbluetoothdevicediscoveryagent.html
- discoveryAgent =new QBluetoothDeviceDiscoveryAgent(this);
- //Set the BLE search time
- discoveryAgent->setLowEnergyDiscoveryTimeout(20000);
- connect (discoveryAgent,SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),this,SLOT(addBlueToothDevicesToList(QBluetoothDeviceInfo)));//After finding the device, add it to the list and display it
- connect (discoveryAgent, SIGNAL(finished()), this, SLOT(scanFinished()));
- connect (discoveryAgent, SIGNAL(canceled()), this, SLOT(scanCanceled()));
- connect (this, SIGNAL(returnAddress(QBluetoothDeviceInfo)), this, SLOT(createCtl(QBluetoothDeviceInfo)));
-
- //Start searching for devices
- discoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
- }
3. Add the scan results to QListWidget - //Slot function corresponding to deviceDiscovered signals
- void Widget::addBlueToothDevicesToList(const QBluetoothDeviceInfo &info)
- {
- if (info.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration) //Get device information and determine whether the device is a BLE device
- {
- //Format device address and device name
- QString label = QString( "%1 %2" ).arg(info.address().toString()).arg(info.name ( ));
- // Check if the device already exists to avoid duplicate addition
- QList<QListWidgetItem *> items = ui->ctrBleList->findItems(label, Qt::MatchExactly);
-
- //If it does not exist, add it to the device list
- if (items.empty())
- {
- QListWidgetItem *item = new QListWidgetItem(label);
- ui->ctrBleList->addItem(item);
- devicesList.append(info);
- }
- }
- }
4. Connect Bluetooth and stop scanning - void Widget::on_btnConnectBle_clicked()
- {
- //Confirm that a Bluetooth device is selected
- if(!ui->ctrBleList->currentItem()->text().isEmpty())
- {
- //Get the selected address
- QString bltAddress = ui->ctrBleList->currentItem()->text(). left (17);
-
- for ( int i = 0; i<devicesList. count (); i++)
- {
- //Address comparison
- if(devicesList. at (i).address().toString(). left (17) == bltAddress)
- {
- QBluetoothDeviceInfo choosenDevice = devicesList. at (i);
- //Send custom signals==>Execute slots:createCtl
- emit returnAddress(choosenDevice);
- //Stop the search service
- discoveryAgent->stop();
- break;
- }
- }
- }
- }
5. Get features - void Widget::searchCharacteristic()
- {
- if(m_bleServer)
- {
- QList<QLowEnergyCharacteristic> list=m_bleServer->characteristics();
- qDebug()<< "[xiaohage]list.count()=" << list.count ();
- //Traverse characteristics
- for ( int i=0;i<list. count ();i++)
- {
- QLowEnergyCharacteristic c= list.at (i);
- /*Returns true if the QLowEnergyCharacteristic object is valid, otherwise returns false */
- if(c.isValid())
- {
- // Return the properties of the feature.
- // These attributes define the access permissions of the characteristic.
- if(c.properties() & QLowEnergyCharacteristic::WriteNoResponse || c.properties() & QLowEnergyCharacteristic::Write)
- {
- ui->ctrSystemLogInfo->insertPlainText( "\nHas write permission!" );
- m_writeCharacteristic = c; //Save write permission characteristics
- if(c.properties() & QLowEnergyCharacteristic::WriteNoResponse)
- {
- m_writeMode = QLowEnergyService::WriteWithoutResponse;
- }
- else
- {
- m_writeMode = QLowEnergyService::WriteWithResponse;
- }
- }
-
- if(c.properties() & QLowEnergyCharacteristic:: Read )
- {
- m_readCharacteristic = c; //Save read permission characteristics
- }
-
- // A descriptor defines how a characteristic is configured by a specific client.
- m_notificationDesc = c.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration);
- //value is true
- if(m_notificationDesc.isValid())
- {
- //Write descriptor
- m_bleServer->writeDescriptor(m_notificationDesc, QByteArray::fromHex( "0100" ));
- ui->ctrSystemLogInfo->insertPlainText( "\nWrite descriptor!" );
- }
- }
- }
- }
- }
6. Sending Data writeCharacteristic() method to send data to the BLE device. Click the "Send" button in the interface to send the "Hello World" string. - void Widget::SendMsg(QString text)
- {
- QByteArray array=text.toLocal8Bit();
-
- m_bleServer->writeCharacteristic(m_writeCharacteristic,array, m_writeMode);
- }
-
- void Widget::on_btnSendData_clicked()
- {
- SendMsg( "Hello World" );
- }
7. Write data Receive messages received by Bluetooth through the Bluetooth QLowEnergyService::characteristicRead callback interface. - void Widget::BleServiceCharacteristicRead(const QLowEnergyCharacteristic &c,const QByteArray &value)
- {
- Q_UNUSED(c)
-
- ui->ctrSystemLogInfo->insertPlainText( "\nWhen a characteristic read request successfully returns its value: " );
- ui->ctrSystemLogInfo->insertPlainText(QString(value));
- }
8. Disconnect - Widget::~Widget()
- {
- if(!(m_BLEController->state() == QLowEnergyController::UnconnectedState))
- m_BLEController->disconnectFromDevice(); //Disconnect from the device
-
- delete ui;
- }
Interface layout Results If "Cannot connect to remote device." appears, you can click the "Connect" button to reconnect. Serial port assistant and application output To do This example is just to demonstrate the communication process between an Android phone and the TB-02-kit module. There are some areas that need to be improved in the program. For example, a "scan" button should be added instead of directly performing Bluetooth scanning during software startup. In this case, Bluetooth power-on needs to be completed before the software is started. The robustness of the program also needs to be improved. For example, occasionally the module may not be connected properly, and you will need to click the "Connect" button again. You can improve these tasks by yourselves. With this knowledge, the next step is to combine Android phones and TB-02-kit modules to achieve remote control of STM32 devices. Qt Tips 1. Qt Creator program output window filters debugging information 2. Add events to Button Select "Go to slot..." in the right-click menu of the Button control, then select the signal in the pop-up list: "clicked()", and then click the OK button to enter its event function. References Qt official documentation: https://doc.qt.io/qt-5/classes.html This article is reprinted from the WeChat public account "Embedded from 0 to 1", which can be followed through the following QR code. To reprint this article, please contact the Embedded from 0 to 1 public account. |