Serial bluetooth terminal как работает

от admin

ide: Serial Bluetooth Terminal

By Thomas Gumbricht January 25, 2020 January 25, 2020 Tweet Like +1

Introduction

In this post you will use the Android app Serial Bluetooth Terminal by Kai Morich for connecting to your Arduino with Bluetooth and receive serial data from a sensor. It will be like replacing the Arduino IDE terminal window with your Android device.

Get started

Go to Google play store and search for “Serial Bluetooth Terminal”. Install the app on your Andriod device.

If you now pair your Arduino bluetooth (whether classic of BLE does not matter), your serial output will show up in the Serial Bluetooth Terminal on your phone.

Bluetooth модуль HM-10 (ZS-040). Урок 14. Ардуино

Bluetooth модуль HM-10 (ZS-040)

Привет! Как известно, все становится лучше, если добавить bluetooth. Поэтому пришло время добавить к нашим проектам bluetooth модуль HM-10. И попробовать управлять схемой на Ардуино через телефон.

В этом уроке мы будем модифицировать схему с rgb светодиодом. Поэтому, посмотрите урок с ней, если уже забыли или пропустили его.

Для того, чтобы выполнить этот урок нам понадобиться

  • Ардуино UNO
  • Макетная плата
  • Перемычки
  • 3 Резистора номиналом 220 Ом
  • 3 Резистора номиналом 1 кОм
  • RGB Светодиод
  • Bluetooth модуль HM-10
  • Кабель USB

В прошлом уроке мы настроили схему на Ардуино, которая управляется из последовательного порта. Мы записывали в последовательный порт данные через программу на Processing и плата Ардуино управляла цветом на rgb светодиоде.

Теперь заменим Processing программу на bluetooth модуль и программу в телефоне.

Программа и схема

Соберем схему для управления rgb светодиода и добавим в схему bluetooth модуль.

Принципиальная схема подключения bluetooth модуля

Контакт TXD подключаем напрямую к контакту 8 Ардуино. А RXD подключаем к 9 контакту через делитель напряжения. Используем сопротивление 1 кОм с одной стороны и 2 кОм с другой.

После подключения питания к Ардуино, лампочка на модуле начнет мигать. Значит питание к нему подключено, и, первоначально, все работает правильно.

После этого уже можно попробовать найти его среди других Bluetooth устройств. С помощью компьютера или телефона. В моем случае, он определяется как BT05

Поиск bluetooth устройств в windows 10

Но сначала напишем программу для Ардуино и загрузим на плату.

В программе используем библиотеку для bluetooth. И создадим все переменные, которые понадобятся в будущем.

В функции setup() настроим основные параметры программы. Включим последовательные порты на ардуино и на bluetooth.

Сразу отправим тестовые сообщения в оба монитора.

Самое интересное будет в цикле loop(). Будем считывать информацию с последовательного порта bluetooth. Считывается только один символ. Поэтому нужно подумать, как считать всю строку и обработать уже ее. Для этого найдем символ перевода строки ‘\n’ . Все, что было до этого символа соберем в одну строку.

Кроме того, мы собираем только цифры, поэтому всю строку можно представить как число. Ограничим это число функцией constrain(), чтобы можно было написать в программе что угодно, но Ардуино записал на пин корректное значение.

С помощью счетчика цикла i будем переключать контакты rgb светодиода и сбрасывать счетчик, когда он будет равен 3.

Не забудем сбросить переменную для формирования строки перед следующим вводом данных.

Полный текст программы

Serial Bluetooth Terminal

Теперь нам понадобиться клиент для Android, который сможет подключиться к последовательному порту через bluetooth. Найдем такое приложение в Play Market.

Найдем наш модуль в меню devices. И попробуем к нему подключиться.

Наше устройство на экране поиска в Serial Bluetooth Terminal

Попробуем подключиться, и если все правильно, то увидим сообщение Connected.

Подключились к нашему модулю

И наконец, отправим на наш модуль команды. На которые должна среагировать программа в Ардуино и изменить цвет rgb светодиода.

Задаем белый цвет rgb светодиода через приложение

Каждая введенная цифра отвечает за свой цвет на rgb светодиоде. Как вы помните, цвета переключаются в цикле. Если на два цвета отправить 0, а на последний 250, то гореть должен только один цвет.

Заключение

Мы научились использовать Bluetooth модуль HM-10. И подключили его к Ардуино. Это дает возможности управлять схемой на Ардуино с помощью программы в телефоне или компьютере без подключенных проводов. Естественно, возможности использовать bluetooth почти не ограничены. Постараемся использовать его чаще в наших проектах.

Подключение Bluetooth модуля HC-05 к NodeMCU ESP8266

В настоящее время технология Bluetooth неотъемлемой частью большинства цифровых устройств в современном мире: смартфонов, ноутбуков, часов, финтес-браслетов и т.д. Она стала доминирующей технологией для радиосвязи на короткие расстояния практически сразу после своего изобретения. Хотя в большинстве случаев технология Bluetooth используется как замена кабельного соединения между устройствами, она на самом деле является универсальным мостом для существующих сетей передачи данных и механизмом соединения равноправных/одноранговых (ad hoc) устройств в различных конфигурациях.

Внешний вид подключения Bluetooth модуля HC-05 к NodeMCU ESP8266

В данной статье мы рассмотрим подключение Bluetooth модуля HC-05 к популярному сейчас Wi-Fi модулю ESP8266 и будем управлять его встроенным светодиодом удаленно, с помощью передачи команд по протоколу Bluetooth. Светодиод в нашем проекте можно заменить, к примеру, на реле, с помощью которого можно управлять различными устройствами в системах умного дома.

Ранее на нашем сайте мы рассматривали использование Bluetooth модулей HC-05 и HC06 в следующих проектах:

Необходимые компоненты

Аппаратное обеспечение

  1. NodeMCU ESP8266 (купить на AliExpress).
  2. Bluetooth модуль HC-05 (купить на AliExpress).

Программное обеспечение

  1. Arduino IDE.
  2. Serial Bluetooth Terminal (приложение Android) – для мониторинга данных Bluetooth на смартфоне.

Схема проекта

Схема подключения Bluetooth модуля HC-05 к NodeMCU ESP8266 представлена на следующем рисунке.

Схема подключения Bluetooth модуля HC-05 к NodeMCU ESP8266

Для использования технологии Bluetooth модулю ESP8266 необходим внешний Bluetooth модуль поскольку он не имеет встроенного Bluetooth модуля как, к примеру, ESP32.

Внешний вид собранной конструкции проекта

Bluetooth модуль HC-05

Вешний вид обеих сторон Bluetooth модуля HC-05 показан на следующем рисунке.

Вешний вид обеих сторон Bluetooth модуля HC-05

HC-05 является Bluetooth модулем с последовательной связью. Его можно настроить с помощью AT. Он может работать в различных конфигурациях: Master (ведущий), Slave (ведомый), Loop back). В нашем проекте он будет использоваться в качестве ведомого устройства.

Технические характеристики Bluetooth модуля HC-05:

  • типовая чувствительность: -80dBm;
  • скорость передачи данных: 9600 бод, 8 бит данных, 1 стоповый бит, нет бита четности;
  • pin код для автоматического соединения: “1234” или “0000”;
  • 6 контактов;
  • контакты Vcc и Gnd используются для подачи питания на модуль;
  • контакты Tx и Rx используются для взаимодействия с микроконтроллером;
  • контакт Enable для активации модуля, когда на нем low – модуль деактивирован (отключен);
  • контакт State работает как индикатор состояния модуля. Когда модуль не соединен с другим Bluetooth устройством, светодиод мигает постоянно. Когда он соединен с другим Bluetooth модулем – светодиод мигает с постоянной задержкой 2 секунды.

Использование Serial Bluetooth Terminal

Данное Android приложение является очень простым в использовании и требует несколько простых шагов для своей настройки.

По Bluetooth соедините ваш смартфон с модулем HC-05. По умолчанию код для подключения ‘0000’ или ‘1234’ (в большинстве случаев ‘1234’).

Скачайте, установите и запустите на выполнение приложение Serial Bluetooth Terminal. Затем откройте вкладку устройства и найдите в нем модуль HC-05. Если модуль HC-05 не отображается в списке устройств проверьте правильно ли он запитан.

Главный экран приложения Serial Bluetooth Terminal Список подключенных устройств в приложении Serial Bluetooth Terminal

После выбора модуля HC-05 в списке устройств произойдет подключение к нему приложения. Теперь напечатайте любое сообщение в поле ввода и передайте его. После этого сообщение должно появиться в окне монитора последовательной связи Arduino IDE.

Передача команды в приложении Serial Bluetooth Terminal Ввод команды в приложении Serial Bluetooth Terminal

Далее перейдем к написанию программы для нашего проекта.

Объяснение программы для модуля ESP8266

Полный код программы приведен в конце статьи, здесь же мы кратко рассмотрим его основные фрагменты.

В данном проекте мы будем использовать аппаратный и программный порты последовательной связи модуля ESP8266. Аппаратный порт будет использоваться для взаимодействия с монитором последовательной связи Arduino IDE, а программный – для взаимодействия с модулем HC-05.

Первым делом подключим в программе библиотеку последовательной связи (Software Serial library).

ESP32 Bluetooth Classic with Arduino IDE – Getting Started

The ESP32 comes with Wi-Fi, Bluetooth Low Energy and Bluetooth Classic. In this tutorial, you’ll learn how to use ESP32 Bluetooth Classic with Arduino IDE to exchange data between an ESP32 and an Android smartphone.

ESP32 Bluetooth Classic and Android Smartphone BT

We’ll control an ESP32 output, and send sensor readings to an Android smartphone using Bluetooth Classic.

Note: this project is only compatible with Android smartphones.

Watch the Video Tutorial

You can watch the video tutorial or keep reading this page for the written instructions.

Bluetooth Classic with ESP32

At the moment, using Bluetooth Classic is much more simpler than Bluetooth Low Energy. If you’ve already programmed an Arduino with a Bluetooth module like the HC-06, this is very similar. It uses the standard serial protocol and functions.

hc-05 bluetooth module arduino ESP32

In this tutorial, we’ll start by using an example that comes with the Arduino IDE. Then, we’ll build a simple project to exchange data between the ESP32 and your Android smartphone.

Parts Required

To follow this tutorial, you need the following parts:

    (read Best ESP32 development boards)
  • Android Smartphone with Bluetooth
Читать:
Что такое асимметричный ток

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!

Bluetooth Terminal Application

To proceed with this tutorial, you need a Bluetooth Terminal application installed in your smartphone.

We recommend using the Android app “Serial Bluetooth Terminal” available in the Play Store.

bluetooth serial application esp32

Serial to Serial Bluetooth

We’ll program the ESP32 using Arduino IDE, so make sure you have the ESP32 add-on installed before proceeding:

  • Windows:instructions – ESP32 Board in Arduino IDE
  • Mac and Linux:instructions – ESP32 Board in Arduino IDE

Open your Arduino IDE, and go to File > Examples > BluetoothSerial > SerialtoSerialBT.

The following code should load.

How the Code Works

This code establishes a two-way serial Bluetooth communication between two devices.

The code starts by including the BluetoothSerial library.

The next three lines check if Bluetooth is properly enabled.

Then, create an instance of BluetoothSerial called SerialBT :

setup()

In the setup() initialize a serial communication at a baud rate of 115200.

Initialize the Bluetooth serial device and pass as an argument the Bluetooth Device name. By default it’s called ESP32test but you can rename it and give it a unique name.

In the loop() , send and receive data via Bluetooth Serial.

In the first if statement, we check if there are bytes being received in the serial port. If there are, send that information via Bluetooth to the connected device.

SerialBT.write() sends data using bluetooth serial.

Serial.read() returns the data received in the serial port.

The next if statement, checks if there are bytes available to read in the Bluetooth Serial port. If there are, we’ll write those bytes in the Serial Monitor.

It will be easier to understand exactly how this sketch works in the demonstration.

Testing the Code

Upload the previous code to the ESP32. Make sure you have the right board and COM port selected.

After uploading the code, open the Serial Monitor at a baud rate of 115200. Press the ESP32 Enable button.

After a few seconds, you should get a message saying: “The device started, now you can pair it with bluetooth!”.

ESP32 Bluetooth Classic and Android Smartphone Demonstration

Go to your smartphone and open the “Serial Bluetooth Terminal” app. Make sure you’ve enable your smartphone’s Bluetooth.

To connect to the ESP32 for the first time, you need to pair a new device.
Go to Devices.

ESP32 Bluetooth Classic and Android Application Serial Bluetooth Terminal

Click the settings icon, and select Pair new device. You should get a list with the available Bluetooth devices, including the ESP32test. Pair with the ESP32test.

ESP32 Bluetooth Classic and Android Application Serial Bluetooth Terminal Pair new device

Then, go back to the Serial Bluetooth Terminal. Click the icon at the top to connect to the ESP32. You should get a “Connected” message.

ESP32 Bluetooth Classic and Android Application Serial Bluetooth Terminal connected

After that, type something in the Serial Bluetooth Terminal app. For example, “Hello”.

ESP32 Bluetooth Classic and Android Application Serial Bluetooth Terminal Demonstration

You should instantly receive that message in the Arduino IDE Serial Monitor.

ESP32 Bluetooth Classic demonstration serial monitor Arduino IDE

You can also exchange data between your Serial Monitor and your smartphone. Type something in the Serial Monitor top bar and press the “Send” button.

ESP32 Bluetooth Classic demonstration serial monitor Arduino IDE

You should instantly receive that message in the Serial Bluetooth Terminal App.

ESP32 Bluetooth Classic and Android Application Serial Bluetooth Terminal Demonstration

Exchange Data using Bluetooth Serial

Now that you know how to exchange data using Bluetooth Serial, you can modify the previous sketch to make something useful. For example, control the ESP32 outputs when you receive a certain message, or send data to your smartphone like sensor readings.

The project we’ll build sends temperature readings every 10 seconds to your smartphone. We’ll be using the DS18B20 temperature sensor.

ds18b20 temperature sensor

Through the Android app, we’ll send messages to control an ESP32 output. When the ESP32 receives the led_on message, we’ll turn the GPIO on, when it receives the led_off message, we’ll turn the GPIO off.

Schematic

Before proceeding with this project, assemble the circuit by following the next schematic diagram.

Connect an LED to GPIO25 , and connect the DS18B20 data pin to GPIO32 .

Bluetooth Classic ESP32 communication

To work with the DS18B20 temperature sensor, you need to install the One Wire library by Paul Stoffregen and the Dallas Temperature library. Follow the next instructions to install these libraries, if you haven’t already.

One Wire library

    . You should have a .zip folder in your Downloads
  1. Unzip the .zip folder and you should get OneWire-master folder
  2. Rename your folder from OneWire-master to OneWire
  3. Move the OneWire folder to your Arduino IDE installation libraries folder
  4. Finally, re-open your Arduino IDE

Dallas Temperature library

    . You should have a .zip folder in your Downloads
  1. Unzip the .zip folder and you should get Arduino-Temperature-Control-Library-master folder
  2. Rename your folder from Arduino-Temperature-Control-Library-master to DallasTemperature
  3. Move the DallasTemperaturefolder to your Arduino IDE installation libraries folder
  4. Finally, re-open your Arduino IDE

After assembling the circuit and installing the necessary libraries, copy the following sketch to your Arduino IDE.

How the Code Works

Let’s take a quick look at the code and see how it works.

Start by including the necessary libraries. The BluetoothSerial library for Bluetooth, and the OneWire and DallasTemperature for the DS18B20 temperature sensor.

Create a BluetoothSerial instance called SerialBT .

Create a variable called ledPin to hold the GPIO you want to control. In this case, GPIO25 has an LED connected.

Define the DS18B20 sensor pin and create objects to make it work. The temperature sensor is connected to GPIO32 .

Create an empty string called message to store the received messages.

Create a char variable called incomingChar to save the characters coming via Bluetooth Serial.

The temperatureString variable holds the temperature readings to be sent via Bluetooth.

Create auxiliar timer variables to send readings every 10 seconds.

setup()

In the setup() , set the ledPin as an output.

Initialize the ESP32 as a bluetooth device with the “ESP32” name.

In the loop() , send the temperature readings, read the received messages and execute actions accordingly.

The following snippet of code, checks if 10 seconds have passed since the last reading. If it’s time to send a new reading, we get the latest temperature and save it in Celsius and Fahrenheit in the temperatureString variable.

Then, to send the temperatureString via bluetooth, use SerialBT.println() .

The next if statement reads incoming messages. When you receive messages via serial, you receive a character at a time. You know that the message ended, when you receive \n .

So, we check if there’s data available in the Bluetooth serial port.

If there is, we’ll save the characters in the incomingChar variable.

If the incomingChar is different than \n , we’ll concatenate that char character to our message.

When we’re finished reading the characters, we clear the message variable. Otherwise all received messages would be appended to each other.

After that, we have two if statements to check the content of the message. If the message is led_on , the LED turns on.

If the message is led_off , the LED turns off.

Testing the Project

Upload the previous sketch to your ESP32 board. Then, open the Serial Monitor, and press the ESP32 Enable button. When you receive the following message, you can go to your smartphone and connect with the ESP32.

Testing ESP32 Bluetooth Classic Project Code Example

Then, you can write the“led_on” and “led_off” messages to control the LED.

Testing ESP32 Bluetooth Classic Project Code Example

The application has several buttons in which you can save default messages. For example, you can associate M1 with the “led_on” message, and M2 with the “led_off” message.

Now, you are able to control the ESP32 GPIOs.

At the same time, you should be receiving the temperature readings every 10 seconds.

Wrapping Up

In summary, the ESP32 supports BLE and Bluetooth Classic. Using Bluetooth Classic is as simple as using serial communication and its functions.

If you want to learn how to use BLE with the ESP32, you can read our guide:

We hope you’ve found this tutorial useful. For more projects with the ESP32 you can check our project’s compilation: 20+ ESP32 Projects and Tutorials.

This tutorial is a preview of the “Learn ESP32 with Arduino IDE” course. If you like this project, make sure you take a look at the ESP32 course page where we cover this and a lot more topics with the ESP32.

Похожие публикации