Abstract: Some time ago with QT to write a serial debugging assistant, feel can also. Because QT is cross-platform, the same set of code can run on Windows, Linux, and Android phones. And you don’t need to change anything, the compiler will automatically generate it for you, which is very convenient. Since I can run on the phone, then I change the serial port to Bluetooth is a Bluetooth APP, isn’t it? Dry dry, on the Internet about QT development of Bluetooth has related information, so it is integrated with all aspects of information, integration of a Bluetooth APP.

You don’t need any Java knowledge to make this app. You just need to know the basic C++ foundation of QT. For the code, I’ll put a link at the end of the article. Only you have a Bluetooth module (HC-05) and an Android phone to make the Bluetooth APP work.

I. Software and hardware platforms

1.1 Hardware Platform

1. Bluetooth: HC-05, (sold on Taobao), its interface is the same as the serial port, we use TX,RX,GND,VCC four pins. Connect to the PC with the lower computer or the CH340G TTL to USB module. Bluetooth working in serial mode can be adjusted by AT command. For details, please refer to the bluetooth supporting documentation. The most important thing is to set bluetooth to slave mode, otherwise the search link of Android phone cannot be found.

2. Android phones: I have used one Android phone, one is Huawei Honor V10 and Android version 10.

1.2 Software Platform

The Qt version of this project is 5.13.7, and the system is Windows 10 X64

Two, the basic introduction of software

Because it is the first time to do Bluetooth, I will make a very simple prototype, which can realize bluetooth status detection, Bluetooth switch, Bluetooth scan and Bluetooth pairing link, and can complete data transceiver like serial port assistant. Figure, is the beginning of the most simple software interface, the software based on mainwinODW control production, of course, you can choose other, more can define their own class.

! [] (img – blog. Csdnimg. Cn / 20210323140… =350×700)

After bluetooth is enabled and scanned, the MAC address and name of Bluetooth will be displayed in the List. Double-click bluetooth in the List to enter the slot function of The Actived signal connection and perform bluetooth pairing. After the connection is established, data communication can be carried out just like the serial port.

Third, Bluetooth development

3.1 Preparation of project documents

If you want to use Bluetooth, you need to import it into your.pro file, and you need to add this to your.pro file:

QT += bluetooth
Copy the code

If this is not the case, containing the header file in the Bluetooth directory will prompt you that the file cannot be found. The next step is to include some bluetooth header files:

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

Define bluetooth-related handles in your class:

QBluetoothDeviceDiscoveryAgent *discoveryAgent;// Use it to search for nearby Bluetooth
QBluetoothLocalDevice *localDevice;// Perform operations on local devices, such as opening and closing devices, etc
QBluetoothSocket *socket;// It is used for bluetooth pairing and data transmission
Copy the code

The first discoveryAgent is used to search the surrounding bluetooth, and the localDevice is used to operate the localDevice, such as turning on and off the device. Sockets are used for Bluetooth pairing and data transmission. We’re going to use these three here.

3.2 Bluetooth switch and visibility Settings

In the constructor, allocate memory for localDevice using the new operator.

localDevice = new QBluetoothLocalDevice();
Copy the code

1) Bluetooth switch

How do we turn Bluetooth on and off? I switch bluetooth on and off in the slot functions of the Open button and the close button. localDevice->powerOn(); The method call opens the local Bluetooth device. Before turning bluetooth on, check whether the phone has turned Bluetooth on. If not, turn it on. If it does, it will remind you that Bluetooth is turned on.

void MainWindow::on_pushButton_openBLE_clicked(a)
{
    if( localDevice->hostMode() == QBluetoothLocalDevice::HostPoweredOff)// Bluetooth is not enabled
    {
        localDevice->powerOn();// Call to open the local Bluetooth device
        discoveryAgent->start();// Start scanning bluetooth devices
    }
    else
    {
         QMessageBox::information(this, tr("Success"), tr("Bluetooth enabled.")); }}Copy the code

Close button slot function:

void MainWindow::on_pushButton_closeBLE_clicked(a)
{
    socket->close();
    QMessageBox::information(this, tr("Success"), tr("Disconnected"));
}
Copy the code

3.3 Search for Bluetooth devices

The discoveryAgent class is instantiated to find using Bluetooth devices. We need in the constructor of discoveryAgent = new QBluetoothDeviceDiscoveryAgent (); Allocate memory. You can then use the methods of this class to look up Bluetooth. In addition, there is also a signal and slot link.

connect(discoveryAgent,
		SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
		this,
		SLOT(addBlueToothDevicesToList(QBluetoothDeviceInfo))
		);
Copy the code

When we found that the equipment, the deviceDiscovered signal is triggered, into addBlueToothDevicesToList function. In the software interface above, the control under our top Bluetooth list is ListIte control. Here we make a slot function to print the found devices to this list.

// Displays the bluetooth device found on the ListWidget
void MainWindow::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());
        /* Bluetooth status pairingStatus, Pairing Enumerated type * 0:Unpaired Paired * 1:Paired but not authorized * 2:AuthorizedPaired and authorized */
        if (pairingStatus == QBluetoothLocalDevice::Paired || pairingStatus == QBluetoothLocalDevice::AuthorizedPaired )
            item->setTextColor(QColor(Qt::red));
        elseitem->setTextColor(QColor(Qt::black)); ui->listWidget->addItem(item); }}Copy the code

When clicking on an item in listItem, the background color will be flipped, double-clicking on the item will establish a connection to the bluetooth device, and there is an Actived slot function that will connect to the Bluetooth device.

3.4 Establishing bluetooth connection

Before we talk about bluetooth device connection, we have to mention a very important concept, which is bluetooth Uuid, quoting Baidu:

In Bluetooth, each service and service attribute is uniquely verified by a global unique Identifier (UUID). As its name implies, each such identifier is guaranteed to be unique in space and time. The UUID class can manifest as a short (16 or 32 bit) and long (128 bit) UUID. He provides constructors to create classes using strings and 16-bit or 32-bit values, a method to compare two UUids (if both are 128-bit), and a method to convert a UUID to a String. UUID instances are immutable, and only services identified by UUID can be discovered.

On Linux you can generate a UUID value with the command uuidgen -t. On Windows, run the uuidgen command. The UUID looks like this: 2D266186-01FB-47C2-8D9F-10b8EC891363. When using the generated UUID to create a UUID object, you can remove the hyphen.

In our project, the mode used is serial mode, we need to establish a mechanism to store Uuid, as follows:

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

This string contains the Uuid of serial mode. If you develop bluetooth that uses serial port, you can Copy it directly. If you use other modes, you can find the Uuid of this mode by yourself.

To establish a connection using Bluetooth, you need to establish the Bluetooth socket service. Add the memory allocated to the socket in the constructor. Note that the parameters in the constructor need a given schema.

socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
Copy the code

In Qt documentation, there are 3 modes, specific how to do not extend here, readers need to consult the document. But RfcommProtocol, which is analog to RS232 mode, I call serial mode. When you double-click on an item in the ItemList control, you will access the Actived slot function to connect to bluetooth. In the itemList we print a Bluetooth MAC address, which we save in an instantiation of the QBluetoothAddress class and pass the address to the socket as a link.

// Bluetooth connection
void MainWindow::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("Tip"),tr("Device being connected..."));
    socket->connectToService(address, QBluetoothUuid(serviceUuid) ,QIODevice::ReadWrite);
}
Copy the code

We will get the address information by manipulating the string. Through the socket – > connectToService (…). “, pass in the address, Uuid, and Bluetooth mode. When this is done, the Android phone will start to connect to the Bluetooth device of your choice.

The socket also provides a variety of slot functions, such as successful connection signal, successful disconnect signal, here in the slot function can do some examples, here is an example:

// The search for the device will stop after the bluetooth connection is successful
connect(socket,SIGNAL(connected()),this,SLOT(connectOK()));
// The bluetooth connection is disconnected
connect(socket,SIGNAL(disconnected()),this,SLOT(connectNot()));
// When receiving data from the upper computer, it will trigger the receiving data function
connect(socket,SIGNAL(readyRead()),this,SLOT(readBluetoothDataEvent()));
// The connection succeeded
void MainWindow::connectOK(a)
{
    discoveryAgent->stop();  // Stop the search device
    QMessageBox::information(this, tr("Success"), tr("Connection successful!"));
}
// Connection failed
void MainWindow::connectNot(a)
{
    QMessageBox::information(this, tr("Tip"), tr("Disconnected"));
}
Copy the code

3.5 Sending and receiving Data

Bluetooth sends and receives data through sockets. Sending data is simple:

void Widget::on_pushButton_send_clicked(a)
{
    QByteArray arrayData;
    QString s("Welcome to pay attention to WeChat public number Guoguo young teachers\n");
    socket->write(s.toUtf8());
}
Copy the code

This is done through the socket->write function. After sending it, the serial assistant I used will display the message on the host computer. The serial assistant receives messages, but what about receiving data? In the constructor, we need to create a link between a signal and a slot like this:

connect(socket,
       SIGNAL(readyRead()),
       this,
       SLOT(readBluetoothDataEvent())
       );
Copy the code

The readyRead() signal jumps into the readBluetoothDataEvent.

void Widget::readBluetoothDataEvent(a)
{
    QByteArray line = socket->readAll();
    QString strData = line.toHex();
    comStr.append(strData);
    if(comStr.length() >= 4) 
    {
	    ui->textBrowser_info->append(comStr + "\n"); comStr.clear(); }}Copy the code

This is all the steps of QT to develop a Bluetooth APP. Download the source code and try it!

Public number background reply: Bluetooth car, you can get the download link.

Android Mobile Phone Bluetooth APP development based on QT