Arduino bluetooth connect to android

Урок 15. Bluetooth модуль HC-06 подключение к Arduino. Управление устройствами с телефона.

ГЛАВНАЯ / Уроки и проекты / Урок 15. Bluetooth модуль HC-06 подключение к Arduino. Управление устройствами с телефона.

Очень часто в ваших проектах возникает необходимость в дистанционном управлении или передачи данных с ваших телефонных гаджетов.

Один из самых популярных и распространенных методов обмена данными посредством Bluetooth.

Сегодня мы разберем простые примеры как можно подключить Bluetooth модуль к Arduino и настроить дистанционное управление с телефона.

Нам понадобится:

Схема подключения Bluetooth к Arduino:

Подключать Bluetooth модуль к микроконтроллеру Arduino удобнее всего с помощью проводков ПАПА-МАМА.

Arduino Bluetooth
Pin 1 (TX) RXD
Pin 0 (RX) TXD
GND GND
5V VCC

Будьте внимательны, подключать подключать нужно TX -> RXD ,RX -> TXD.

Теперь необходимо записать пробный код программы:

Во время загрузки скетча необходимо что бы Bluetooth модуль был отключен от микроконтроллера arduino. В противном случае скетч не запишется, потому что связь с Bluetooth модулем происходит по одному и томуже порту RX и TX, что и USB.

int val; int LED = 13; void setup() < Serial.begin(9600); pinMode(LED, OUTPUT); digitalWrite(LED, HIGH); >void loop() < if (Serial.available()) < val = Serial.read(); // При символе "1" включаем светодиод if (val == '1') < digitalWrite(LED, HIGH); >// При символе "0" выключаем светодиод if ( val == '0') < digitalWrite(LED, LOW); >> >

После того как скетч записан и Bluetooth модуль подключен к Arduino, можно перейти к следующему шагу.

Подключение Bluetooth к телефону

Желательно в качестве источника питания для arduino использовать не USB, а внешний Блок питания на 9 В.

  1. Включаем Bluetooth на телефоне и ищем новые устройства
  2. Находим в списке расстройств «HC-06″ и подключаемся к нему.
  3. Телефон спросит пин-код. необходимо ввести «1234» или «0000«
  4. Ура. Устройство подключено.

Теперь нужно скачать bluetooth terminal на ваш телефон. Мы рассмотрим на примере платформы Android.

Вы можете установить разные bluetooth терминалы, как правило они отличаются только разными дизайнами, функционал от этого не меняется. Так же можно найти и терминал и для продуктов ios.

После того как мы установили терминал, запускаем его выбираем наш bluetooth модуль HC-06 и подключаемся к нему.

Пришло время попробовать проект в деле. Пишем в терминале цифру «0» и отправляем. Светодиод L который находится на плате arduino рядом с pin 13, должен погаснуть. Теперь отправим через терминал цифру «1» и светодиод L должен зажечься.

Демонстрация работы:


Домашняя работа:

  • Изменить скетч так, что бы светодиод зажигался и потухал с помощью одной и той же команды например «G».
  • Дописать скетч и научить его преобразовывать текстовые данные приходящие через блютус в цифровые и реализовать димер, зажигать светодиод с помощью ШИМ, на заданную яркость от 0 до 254 приходящую через bluetooth.
Читайте также:  Схема подключения блютуз колонки своими руками

Источник

Arduino Communication with an Android App via Bluetooth

Share

https://analytics.oemsecrets.com/main.php?p=avnet-infineon-jun23&media=banner&table=wallpaper&source=elab&event_link=https%3A%2F%2Fwww.avnet.com%2Fwps%2Fportal%2Febv%2Fproducts%2Fproduct-highlights%2Febv-power-distribution%2Fwebinar%2F%3Futm_campaign%3Dfy23-emea-ebv-supinf%26utm_content%3Dedu-wr-infineonpowerdistributioncampaign2023%26utm_medium%3Dadp%26utm_source%3Doem-electronicslab%26utm_term%3Debv-inf-pwr-distr-bg-ban-elabs-202306

With the arrival of the IoT and the need for control, devices now need to do more than perform the basic functions for which they are built, they need to be capable of communicating with other devices like a mobile phone among others. There are different communication systems which can be adapted for communication between devices, they include systems like WiFi, RF, Bluetooth among several others. Our focus will be on communication over Bluetooth.

Today we will build an Arduino based project which communicates with an app running on a smartphone (Android) via Bluetooth.

For simplicity, the goal of the project is to switch a LED connected to the Arduino using the mobile app. We will be using the HC06 Bluetooth module as the major ingredient in this tutorial.

The HC06 Bluetooth Module is a slave only version of the HC05 Bluetooth module. It has 4 pins and communicates with a microcontroller via serial interface.

The HC06 Bluetooth module is a 3.3v logic level based device and thus if directly connected to the Arduino, will sometimes be unable to process the message received from the Arduino which is a 5v Level logic level device unless there exists some form of level shifting, although the Arduino can easily understand the data being sent from the Bluetooth module since it uses a higher logic level. The level shifting/conversion can be achieved either by use of a voltage divider or a level shifter module (like we did in this tutorial).

The shifter module (shown in the image below) helps with the easy transition from one voltage to the other. The level shifter has two sides, the high voltage side (marked HV) and the low voltage side (Marked LV). The shifter allows you to connect the desired low voltage output on the LV side and the high voltage line also to the HV. More details on connecting the level shifter are discussed in the schematics section.

Required Components

The following components are required for this tutorial;

As usual, the exact components used for this tutorial can be bought by following the link attached to each of them.

Schematics

Connect the components as shown in the schematics below.

As earlier mentioned, the HC06 Bluetooth module is a 3.3v logic level device, to make it compatible with the logic level of the Arduino (which is 5v) we need to use a logic level shifter/converter as shown in the schematics above. To make the schematics a bit clearer, a pin map of the components and their connections is shown below.

Arduino – Logic converter

D10 - RX (HV Side) D11 - Tx (HV Side) Gnd - Gnd 3.3v - LV 5V - HV

HC06 – Logic Converter

Rx - Rx(LV side) Tx - Tx(LV Side) vcc - 5v (same as HV) Gnd - Gnd

With the components connected and the connection verified, we are ready to build the Android app to be used for the actual control of the LED.

Читайте также:  Пионер карозерия настройки блютуз

Android App

The app for this project was designed using the MIT app inventor for the sake of simplicity, but it can also be built using any other platform, used for the development of Android apps.

The MIT App Inventor is a scratch like mobile app development platform and its focus is around making programming easy for everyone, thus instead of writing codes, the app programming is done using drag and drop blocks just like the programming platform “Scratch”.

To build the app created for this project, create a new project and design the UI to look like the image below.

With the UI done, click on blocks and proceed to replicate the blocks below.

compile the app and save as an APK to your computer from which you can transfer to your phone for installation.

The .aia project raw file for the app is part of the files archived in the zip file located under the download section of this tutorial.

The .aia file can be imported into the MIT App inventor workspace and edited to suit your needs and desires.

The APK install ready file is also attached to the zip file, so you can install straight to your phone.

With the app ready, we can now proceed to write the Arduino code to control our device.

Code

The Arduino communicates with the Bluetooth module via serial communication and this makes it really easy to write the code. Since we decided to use software serial and not the Arduino’s hardware serial pins (D0 and D1), we will need the Arduino software serial library. This library gives us the freedom to choose any of the Arduino digital pins as our Rx and Tx pins. The hardware serial pins are the same pins used by the Arduino to communicate with the computer so connecting them to the Bluetooth will cause interference which could hinder the code upload process. Although the pins can be disconnected from the Bluetooth when the code is being uploaded and reconnected after the code has been uploaded but this is not always efficient.

The basic function of the code is to monitor the incoming serial data stream, if it receives a “1”, it turns the LED on and if it receives a “0” it turns the LED off.

To jump in, we will, as usual, give a breakdown of the code to explain each part before the full code is provided. The Arduino code is among the files archived in the zip file under the download section.

Читайте также:  Управлением компьютером через блютуз

The first thing we do while writing the code, as usual, is to import the libraries we will be working with, which in this case is the software serial library.

///////////////////////////////////////////////////////////////// // Arduino Bluetooth Tutorial v1.00 // // Get the latest version of the code here: // // http://educ8s.tv/arduino-bluetooth-tutorial // ///////////////////////////////////////////////////////////////// #include

After importing the library, we then declare a variable to hold the characters received from the Bluetooth and the pin on the Arduino to which the LED is connected. We also initialize the Softwareserial library by indicating the pins that will serve as Rx and Tx.

char c; int LED = 13; SoftwareSerial mySerial(10, 11);

Next, we move to the setup() section where we set the pinMode for the pin to which our LED is connected (output) and we start the serial communication with a baud rate of 9600 which is the baud rate at which most recent versions of the HC06 module communicate.

Next, we move to the major part of the code; the void loop() function. The first thing we do is confirm the availability of data from the Bluetooth module, after which we read the data, and use an if statement to compare it to see if it is a 1 or 0. if the data is 1, we turn the LED high, but if its 0, we turn the LED off.

The Complete code is available below.

///////////////////////////////////////////////////////////////// // Arduino Bluetooth Tutorial v1.00 // // Get the latest version of the code here: // // http://educ8s.tv/arduino-bluetooth-tutorial // ///////////////////////////////////////////////////////////////// #include char c; int LED = 13; SoftwareSerial mySerial(10, 11); void setup() < pinMode(LED, OUTPUT); mySerial.begin(9600); >void loop() < while (!mySerial.available()); c = mySerial.read(); if (c == '1') < digitalWrite(LED, HIGH); >if (c == '0') < digitalWrite(LED, LOW); >>

Demo

Connect, the Arduino to the computer and upload your code. You should see an LED on the Bluetooth begin to flash, this means it is ready to pair. Turn on your phone’s Bluetooth and you should see hc06 after scanning. connect to it and enter the passkey which is usually 1234.

Proceed by launching the app, and click the connect button, it will show the mac address of your hc06. Connect to it and go back to the apps main screen.

After connecting, the app will show connected on the top left corner, you can then check or uncheck the checkbox to turn on or off the led respectively.

That’s it for today’s tutorial guys, If you have any question, suggestion or comment, kindly drop them under the comment section.

The video of this tutorial is available on youtube here.

Источник

Оцените статью
Adblock
detector