- Digitrode
- цифровая электроника вычислительная техника встраиваемые системы
- ESP32 в качестве сервера Bluetooth (BLE)
- Управление ESP32 через BLE
- Интро
- Немного про то, что же такое BLE
- Выводим сообщение на экран
- Тестируем
- Заключение
- ESP32 BLE Server and Client (Bluetooth Low Energy)
- What is Bluetooth Low Energy?
- BLE Server and Client
- Project Overview
- Parts Required
- 1) ESP32 BLE Server
- Schematic Diagram
- Installing BME280 Libraries
- Installing Libraries (VS Code + PlatformIO)
- ESP32 BLE Server – Code
- Importing Libraries
- Choosing Temperature Unit
- BLE Server Name
- BME280 Sensor
- Other Variables
- BLE UUIDs
- setup()
- Testing the ESP32 BLE Server
- 2) ESP32 BLE Client
- Schematic
- Installing the SSD1306, GFX and BusIO Libraries
- Installing Libraries (VS Code + PlatformIO)
- ESP32 BLE Client – Code
- Importing libraries
- Choosing temperature unit
- BLE Server Name and UUIDs
- Declaring variables
- OLED Display
- Temperature and Humidity Variables
- printReadings()
- setup()
- Scan nearby devices
- MyAdvertisedDeviceCallbacks() function
- Connect to the server
- Notify new values
- Display new temperature and humidity readings
- Testing the Project
- Wrapping Up
Digitrode
цифровая электроника вычислительная техника встраиваемые системы
ESP32 в качестве сервера Bluetooth (BLE)
Bluetooth Low Energy (BLE) работает только когда связь активна и остается включенной. Остальное время модуль BLE проводит в режиме сна. Учитывая это, маячки (Beacon) – отличный вариант использования BLE. Для использования BLE можно задействовать недорогой популярный контроллер ESP32.
В этой статье мы поговорим об использовании ESP32 в качестве сервера BLE.
Если рассматривать BLE телефона, наши умные часы или смартфон сначала идентифицируют его как аудиоустройство. Как правило, он также отображает уровень заряда батареи. Это вопрос понимания того, как конкретный используемый UUID может предоставить подробную информацию об устройстве и организовать иерархию для предоставления уровня заряда батареи с помощью Service UUID. Каждый из параметров может иметь свой собственный UUID, и они называются Characteristic UUID. Важно понимать возможности чтения, записи, уведомления и указания, читая официальную техническую документацию.
Далее приведен пример кода для ESP32 в среде Arduino IDE, который создает сервер BLE, который при получении соединения будет периодически отправлять уведомления. В данном коде хорошо показано, как обрабатываются сервер BLE (BLE Server), служба BLE (BLE Service), характеристика BLE (BLE Characteristic) и дескриптор BLE (BLE Descriptor).
Приведенный выше код основан на примере Нила Колбана, портирование на Arduino было осуществлено Evandro Copercini и дальнейшее обновление от chegewara.
Чтобы получить готовый пример использования приложения Android и кода ESP32, сначала установите приложение Android под названием «BatON» из Google Play. Тогда вы можете использовать приведенный далее код.
После загрузки кода откройте приложение Android под названием «BatON». Выполните сопряжение с устройством Bluetooth с именем «BLE Battery». Вы заметите, что «BatON» выдаст вам (ложный) уровень заряда батареи, как и предусмотрено кодом.
К сожалению, проблема со многими проприетарными устройствами BLE заключается в обеспечении безопасности на уровне операционной системы. Например, вы не можете соединить все виды устройств с часами Samsung Galaxy. По этой причине вам понадобятся два ESP32 (один в качестве сервера и один в качестве клиента), чтобы все заработало правильно. Любое универсальное приложение станет похожим на приложение «BatON».
В этой статье была представлена всего лишь идея создания приложения для Android BLE, когда ESP32 используется в качестве сервера BLE, которая может вдохновить на создание действительно полезных и функциональных устройств.
Источник
Управление ESP32 через BLE
Интро
Уже сравнительно давно микроконтроллер ESP32 стал неким стандартом для множества DIY проектов. И действительно, возможность работы с Wi-Fi, Bluetooth, встроенная энергонезависимая память, а так же большое число выводов позволяют сделать массу интересных проектов.
В этой статье, мы поговорим про управление конроллером с помощью BLE используя доступные в AppStore приложения. А в следующей, если она будет, про создание собственного приложения для iOS.
На основе непосредственно контроллера, существует множество плат, с различными интегрируемыми модулями: экраном, модулем для карт памяти и тд. Одной из самых удобных для новичков, которым интересно именно программирование, а не возня с кучей проводков — платформа M5Stack.
Это устройство, в базовой комплектации, включает в себя LCD-дисплей, кардридер, аккумулятор, и три кнопки. Кроме этого, к нему существует множество модулей, подключаемых по принципу «бутерброда».
Не смотря на то, что в данной статье программирование микроконтроллера будет в Arduino IDE, его так же можно программировать с помощью MicroPython, а так же собственной блоковой среды разработки — UiFlow.
Инструкцию по настройке ArduinoIDE, для работы с M5Stack можно найти здесь.
Немного про то, что же такое BLE
BLE — Bluetooth Low Energy, это протокол, который, в отличии от обычного Bluetooth, постоянно находится в спящем режиме, кроме тех случаев, когда идёт непосредственная передача данных. За счёт этого, тратится примерно в 100 раз меньше энергии, что очень важно при использовании встраиваемых устройств с аккумуляторами.
Когда мы используем протокол BLE, мы работаем с сервисами и характеристиками. Это очень напоминает протокол MQTT, где есть топики. У каждого сервиса, есть как минимум одна характеристика. Каждый сервис это просто объем информации: например состояние датчика. Характеристика включает в себя описание себя (что она умеет: читать, писать, является Broadcast-ом) и непосредственно значение.
Каждый элемент, с которым мы работаем: сервис, характеристика должен иметь свой UUID (Universally unique identifier).
Подробнее про BLE можно почитать тут.
В Ардуино, система работа с BLE примерно такая: есть сервер — это само устройство, у сервера есть сервис, а у сервиса уже есть характеристики, в которые и поступают данные. У каждого из них могут быть Callback функции.
Выводим сообщение на экран
Чтобы работать с BLE и M5Stack из Arduino IDE необходимо подключить библиотеки.
Затем сгенерировать как минимум два UUID: один для сервиса, а один для характеристики. Для генерации можно использовать UUID generator.
Создадим сервер и сервис.
Для создания какой-либо характеристики необходимо сделать следующее:
Объявить класс Callback Функция onWrite вызывается, когда в данную характеристику поступает информация. В нашем случае, информация просто выводится на экран.
И добавить новую характеристику к уже существующему сервису, с указанием свойств. Это тоже делается внутри функции setup()
После добавления всех характеристик, важно не забыть запустить сервис, а после этого запустить Advertising.
Полностью исходный код представлен на гитхабе.
Тестируем
Для тестирования была использована программа BLE scanner. В ней можно выбрать устройство, выбрать характеристику и отправить на неё данные в текстовом или байтовом формате.
При запуске необходимо выбрать наше устройство, затем выбрать ту характеристику, с которой мы хотим работать и отправить в неё информацию.
А что же происходит на устройстве? При загрузке на нём отображается такие сообщения:
После подключения телефона — добавляется соответствующая строка:
А когда отправляется сообщение — экран выглядит так:
Заключение
Используя предложенный пример, можно достаточно легко сделать собственный функционал. А с учётом возможностей M5Stack, часть проектов не потребует никакого дополнительного оборудования.
Источник
ESP32 BLE Server and Client (Bluetooth Low Energy)
Learn how to make a BLE (Bluetooth Low Energy) connection between two ESP32 boards. One ESP32 is going to be the server, and the other ESP32 will be the client. The BLE server advertises characteristics that contain sensor readings that the client can read. The ESP32 BLE client reads the values of those characteristics (temperature and humidity) and displays them on an OLED display.
What is Bluetooth Low Energy?
Before going straight to the project, it is important to take a quick look at some essential BLE concepts so that you’re able to better understand the project later on. If you’re already familiar with BLE, you can skip to the Project Overview section.
Bluetooth Low Energy, BLE for short, is a power-conserving variant of Bluetooth. BLE’s primary application is short-distance transmission of small amounts of data (low bandwidth). Unlike Bluetooth that is always on, BLE remains in sleep mode constantly except for when a connection is initiated.
This makes it consume very low power. BLE consumes approximately 100x less power than Bluetooth (depending on the use case). You can check the main differences between Bluetooth and Bluetooth Low Energy here.
BLE Server and Client
With Bluetooth Low Energy, there are two types of devices: the server and the client. The ESP32 can act either as a client or as a server.
The server advertises its existence, so it can be found by other devices and contains data that the client can read. The client scans the nearby devices, and when it finds the server it is looking for, it establishes a connection and listens for incoming data. This is called point-to-point communication.
There are other possible communication modes like broadcast mode and mesh network (not covered in this tutorial).
GATT stands for Generic Attributes and it defines a hierarchical data structure that is exposed to connected BLE devices. This means that GATT defines the way that two BLE devices send and receive standard messages. Understanding this hierarchy is important because it will make it easier to understand how to use BLE with the ESP32.
- Profile: standard collection of services for a specific use case;
- Service: collection of related information, like sensor readings, battery level, heart rate, etc. ;
- Characteristic: it is where the actual data is saved on the hierarchy (value);
- Descriptor: metadata about the data;
- Properties: describe how the characteristic value can be interacted with. For example: read, write, notify, broadcast, indicate, etc.
In our example, we’ll create a service with two characteristics. One for the temperature and another for the humidity. The actual temperature and humidity readings are saved on the value under their characteristics. Each characteristic has the notify property, so that it notifies the client whenever the values change.
Each service, characteristic, and descriptor have a UUID (Universally Unique Identifier). A UUID is a unique 128-bit (16 bytes) number. For example:
There are shortened UUIDs for all types, services, and profiles specified in the SIG (Bluetooth Special Interest Group).
But if your application needs its own UUID, you can generate it using this UUID generator website.
In summary, the UUID is used for uniquely identifying information. For example, it can identify a particular service provided by a Bluetooth device.
For a more detailed introduction about BLE, read our getting started guide:
Project Overview
In this tutorial, you’re going to learn how to make a BLE connection between two ESP32 boards. One ESP32 is going to be the BLE server, and the other ESP32 will be the BLE client.
The ESP32 BLE server is connected to a BME280 sensor and it updates its temperature and humidity characteristic values every 30 seconds.
The ESP32 client connects to the BLE server and it is notified of its temperature and humidity characteristic values. This ESP32 is connected to an OLED display and it prints the latest readings.
This project is divided into two parts:
Parts Required
Here’s a list of the parts required to follow this project:
ESP32 BLE Server:
ESP32 BLE Client:
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
1) ESP32 BLE Server
In this part, we’ll set up the BLE Server that advertises a service that contains two characteristics: one for temperature and another for humidity. Those characteristics have the Notify property to notify new values to the client.
Schematic Diagram
The ESP32 BLE server will advertise characteristics with temperature and humidity from a BME280 sensor. You can use any other sensor as long as you add the required lines in the code.
We’re going to use I2C communication with the BME280 sensor module. For that, wire the sensor to the default ESP32 SCL ( GPIO 22 ) and SDA ( GPIO 21 ) pins, as shown in the following schematic diagram.
Installing BME280 Libraries
As mentioned previously, we’ll advertise sensor readings from a BME280 sensor. So, you need to install the libraries to interface with the BME280 sensor.
You can install the libraries using the Arduino Library Manager. Go to Sketch > Include Library > Manage Libraries and search for the library name.
Installing Libraries (VS Code + PlatformIO)
If you’re using VS Code with the PlatformIO extension, copy the following to the platformio.ini file to include the libraries.
ESP32 BLE Server – Code
With the circuit ready and the required libraries installed, copy the following code to the Arduino IDE, or to the main.cpp file if you’re using VS Code.
You can upload the code, and it will work straight away advertising its service with the temperature and humidity characteristics. Continue reading to learn how the code works, or skip to the Client section.
There are several examples showing how to use BLE with the ESP32 in the Examples section. In your Arduino IDE, go to File > Examples > ESP32 BLE Arduino. This server sketch is based on the Notify example.
Importing Libraries
The code starts by importing the required libraries.
Choosing Temperature Unit
By default, the ESP sends the temperature in Celsius degrees. You can comment the following line or delete it to send the temperature in Fahrenheit degrees.
BLE Server Name
The following line defines a name for our BLE server. Leave the default BLE server name. Otherwise, the server name in the client code also needs to be changed (because they have to match).
BME280 Sensor
Create an Adafruit_BME280 object called bme on the default ESP32 I2C pins.
The temp , tempF and hum variables will hold the temperature in Celsius degrees, the temperature in Fahrenheit degrees, and the humidity read from the BME280 sensor.
Other Variables
The following timer variables define how frequently we want to write to the temperature and humidity characteristic. We set the timerDelay variable to 30000 milliseconds (30 seconds), but you can change it.
The deviceConnected boolean variable allows us to keep track if a client is connected to the server.
BLE UUIDs
In the next lines, we define UUIDs for the service, for the temperature characteristic in celsius, for the temperature characteristic in Fahrenheit, and for the humidity.
I recommend leaving all the default UUIDs. Otherwise, you also need to change the code on the client side—so the client can find the service and retrieve the characteristic values.
setup()
In the setup() , initialize the Serial Monitor and the BME280 sensor.
Create a new BLE device with the BLE server name you’ve defined earlier:
Set the BLE device as a server and assign a callback function.
The callback function MyServerCallbacks() changes the boolean variable deviceConnected to true or false according to the current state of the BLE device. This means that if a client is connected to the server, the state is true . If the client disconnects, the boolean variable changes to false . Here’s the part of the code that defines the MyServerCallbacks() function.
Start a BLE service with the service UUID defined earlier.
Then, create the temperature BLE characteristic. If you’re using Celsius degrees it sets the following characteristic and descriptor:
Otherwise, it sets the Fahrenheit characteristic:
After that, it sets the humidity characteristic:
Finally, you start the service, and the server starts the advertising so other devices can find it.
The loop() function is fairly straightforward. You constantly check if the device is connected to a client or not. If it’s connected, and the timerDelay has passed, it reads the current temperature and humidity.
If you’re using temperature in Celsius it runs the following code section. First, it converts the temperature to a char variable ( temperatureCTemp variable). We must convert the temperature to a char variable type to use it in the setValue() function.
Then, it sets the bmeTemperatureCelsiusCharacteristic value to the new temperature value ( temperatureCTemp ) using the setValue() function. After settings the new value, we can notify the connected client using the notify() function.
We follow a similar procedure for the Temperature in Fahrenheit.
Sending the humidity also uses the same process.
Testing the ESP32 BLE Server
Upload the code to your board and then, open the Serial Monitor. It will display a message as shown below.
Then, you can test if the BLE server is working as expected by using a BLE scan application on your smartphone like nRF Connect. This application is available for Android and iOS.
After installing the application, enable Bluetooth on your smartphone. Open the nRF Connect app and click on the Scan button. It will find all Bluetooth nearby devices, including your BME280_ESP32 device (it is the BLE server name you defined on the code).
Connect to your BME280_ESP32 device and then, select the client tab (the interface might be slightly different). You can check that it advertises the service with the UUID we defined in the code, as well as the temperature and humidity characteristics. Notice that those characteristics have the Notify property.
Your ESP32 BLE Server is ready!
Go to the next section to create an ESP32 client that connects to the server to get access to the temperature and humidity characteristics and get the readings to display them on an OLED display.
2) ESP32 BLE Client
In this section, we’ll create the ESP32 BLE client that will establish a connection with the ESP32 BLE server, and display the readings on an OLED display.
Schematic
The ESP32 BLE client is connected to an OLED display. The display shows the readings received via Bluetooth.
Wire your OLED display to the ESP32 by following the next schematic diagram. The SCL pin connects to GPIO 22 and the SDA pin to GPIO 21 .
Installing the SSD1306, GFX and BusIO Libraries
You need to install the following libraries to interface with the OLED display:
To install the libraries, go Sketch> Include Library > Manage Libraries, and search for the libraries’ names.
Installing Libraries (VS Code + PlatformIO)
If you’re using VS Code with the PlatformIO extension, copy the following to the platformio.ini file to include the libraries.
ESP32 BLE Client – Code
Copy the BLE client Sketch to your Arduino IDE or to the main.cpp file if you’re using VS Code with PlatformIO.
Continue reading to learn how the code works or skip to the Demonstration section.
Importing libraries
You start by importing the required libraries:
Choosing temperature unit
By default the client will receive the temperature in Celsius degrees, if you comment the following line or delete it, it will start receiving the temperature in Fahrenheit degrees.
BLE Server Name and UUIDs
Then, define the BLE server name that we want to connect to and the service and characteristic UUIDs that we want to read. Leave the default BLE server name and UUIDs to match the ones defined in the server sketch.
Declaring variables
Then, you need to declare some variables that will be used later with Bluetooth to check whether we’re connected to the server or not.
Create a variable of type BLEAddress that refers to the address of the server we want to connect. This address will be found during scanning.
Set the characteristics we want to read (temperature and humidity).
OLED Display
You also need to declare some variables to work with the OLED. Define the OLED width and height:
Instantiate the OLED display with the width and height defined earlier.
Temperature and Humidity Variables
Define char variables to hold the temperature and humidity values received by the server.
The following variables are used to check whether new temperature and humidity readings are available and if it is time to update the OLED display.
printReadings()
We created a function called printReadings() that displays the temperature and humidity readings on the OLED display.
setup()
In the setup() , start the OLED display.
Then, print a message in the first line saying “BME SENSOR”.
Start the serial communication at a baud rate of 115200.
And initialize the BLE device.
Scan nearby devices
The following methods scan for nearby devices.
MyAdvertisedDeviceCallbacks() function
Note that the MyAdvertisedDeviceCallbacks() function, upon finding a BLE device, checks if the device found has the right BLE server name. If it has, it stops the scan and changes the doConnect boolean variable to true . This way we know that we found the server we’re looking for, and we can start establishing a connection.
Connect to the server
If the doConnect variable is true , it tries to connect to the BLE server. The connectToServer() function handles the connection between the client and the server.
It also assigns a callback function responsible to handle what happens when a new value is received.
After the BLE client is connected to the server, you need to active the notify property for each characteristic. For that, use the writeValue() method on the descriptor.
Notify new values
When the client receives a new notify value, it will call these two functions: temperatureNotifyCallback() and humidityNotifyCallback() that are responsible for retrieving the new value, update the OLED with the new readings and print them on the Serial Monitor.
These two previous functions are executed every time the BLE server notifies the client with a new value, which happens every 30 seconds. These functions save the values received on the temperatureChar and humidityChar variables. These also change the newTemperature and newHumidity variables to true , so that we know we’ve received new readings.
Display new temperature and humidity readings
In the loop() , there is an if statement that checks if new readings are available. If there are new readings, we se the newTemperature and newHumidity variables to false , so that we are able to receive new readings later on. Then, we call the printReadings() function to display the readings on the OLED.
Testing the Project
That’s it for the code. You can upload it to your ESP32 board.
Once the code is uploaded. Power the ESP32 BLE server, then power the ESP32 with the client sketch. The client starts scanning nearby devices, and when it finds the other ESP32, it establishes a Bluetooth connection. Every 30 seconds, it updates the display with the latest readings.
Important: don’t forget to disconnect your smartphone from the BLE server. Otherwise, the ESP32 BLE Client won’t be able to connect to the server.
Wrapping Up
In this tutorial, you learned how to create a BLE Server and a BLE Client with the ESP32. You learned how to set new temperature and humidity values on the BLE server characteristics. Then, other BLE devices (clients) can connect to that server and read those characteristic values to get the latest temperature and humidity values. Those characteristics have the notify property, so that the client is notified whenever there’s a new value.
Using BLE is another communication protocol you can use with the ESP32 boards besides Wi-Fi. We hope you found this tutorial useful. We have tutorials for other communication protocols that you may find useful.
Learn more about the ESP32 with our resources:
Источник