Подключение к arduino модулей bluetooth hc-05 и hc-06

Содержание

Что такое bluetooth модуль и его назначение

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

Таким образом, первичное и главное назначение Ардуино блютуз – связь с вашим ПК и\или Андроидом по соответствующему протоколу. Это позволяет не только управлять разнообразными датчиками на микроконтроллере, но и, в случае необходимости, обновлять прошивку.

Полностью перепрошить устройство с его помощью не получится. Помимо этого, Android Arduino bluetooth может обеспечить связь между несколькими МК и приборами. Естественно, для этого на каждом из них должен быть установлен независимый модуль. HC-05 позволяет проложить несколько мостов по типу USAR-bluetooth-USART. При этом само устройство будет восприниматься в качестве ответного на USART. А организовывать связь уже будет аппаратная часть вашего проекта.

Модуль HC-06

У блютуз модуля под Ардуино, есть несколько преимуществ, перед стандартными дополнениями под другие МК:

  1. Инженеру нет необходимости изучать технологию протокола блютуз, чтобы написать софт или начать использовать уже готовые библиотеки.
  2. Простота использования в целом. Вам не нужно будет паять отдельную плату под распределение мощностей, просто подсоедините устройство к уже готовому МК через пины.
  3. Обширный выбор библиотек. Так как Ардуино имеет низкий порог вхождения, под все его модули можно найти большое количество библиотек, разного назначения. Но стоит отметить, что весомая их часть – бесполезны, ибо не работают или работают крайне плохо. Ведь пишет их сообщество, которое не изучало основы алгоритмизации и, в большинстве своём, в принципе, плохо разбирается в программировании. Из-за этого, во многих ситуациях, просто модифицировать чужой софт – не лучшее решение, и значительно проще написать свой.

Сфера же применения RC car Arduino bluetooth – огромна и ограничена лишь вашей фантазией. Например, вы можете купить обычную китайскую гарнитуру, припаять к ней пару модулей под Ардуино, так как они могут функционировать и без МК, и загрузить одну из готовых библиотек. После таких манипуляций наушники можно будет использовать в беспроводном режиме и исчезнет проблема с запутывающимися или гнущимися проводами. Это одна из банальных проблем реализации данного протокола в проекте, на деле их тысячи.

Предназначается bluetooth аудио модуль для бытового и коммерческого применения, чему способствуют его характеристики. Также стоит учитывать, что если вы собираетесь в дальнейшем связываться по одноимённому протоколу с ПК, то на большинстве современных устройств необходимо будет докупить блютуз по USB. Но вы можете также спаять его из МК, создав собственный bluetooth модуль для компьютера. Естественно, это не относится к ноутбукам, где поголовно устанавливаются одноимённые передатчики, и никак модифицировать их уже не требуется.

Подключение через Software Serial

Позволяет подключить модуль к произвольным контактам микроконтроллера. Какие контакты использовать, необходимо указать в панели настроек подключения модуля. Так же в панели настроек указывается скорость передачи данных для порта. Модуль HC-05(06) по умолчанию настроен на скорость 9600 бит/сек. Скорость работы модуля может быть изменена при помощи AT команд (требует специальных знаний), но если вы не изменяли скорость, установите значение по умолчанию, т.е. 9600 бит/сек.

Есть некоторые ограничения на использование контакта RX для плат Arduino. Ограничения связаны с поддержкой прерываний на соответствующих контактах микроконтроллера.

  • Arduino UNO и Nano для RX нельзя использовать контакт 13(LED);
  • Arduino Mega и Mega2560 для RX можно использовать только следующие контакты: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8(62), A9(63), A10(64), A11(65), A12(66), A13(67), A14(68), A15(69);
  • Arduino Leonardo и Micro для RX можно использовать только следующие контакты: 8, 9, 10, 11, 14, 15, 16;

Так же при использовании SoftwareSerial вы должны принять следующие ограничения:

  • Нет возможности работы на больших скоростях передачи данных. Не рекомендуем использовать скорость соединения более 38400 бит/сек.
  • Некоторые библиотеки, которые так же используют прерывания, могут работать не корректно, или же их использование может сделать неработоспособным данный способ подключения. Например библиотека Servo будет подергивать сервоприводы.

Пример подключения модуля HC-05(06) для SoftwareSerial к контактам 2(RX) и 3(TX) на рисунке

Обратите внимание, что необходимо контакты подключить перекрестием, т.е. контакт Arduino 2(RX) к контакту TX модуля, и контакт 3(TX) к контакту RX модуля

Подключение модуля HC-06

Для соединения модуля HC-06 или подобного с Ардуино достаточно подключить его к питанию 5 V и GND, а выводы RXD и TXD соединить крест накрест с соответствующими выводами Ардуино. То есть RXD -> Tx, а TXD -> Rx.

Выводы модуля HC-06

Важный момент! Базовые версии Ардуино имеют один UART и он используется для связи по USB (для программирования), поэтому при включенном Bluetooth модуле общаться по USB не удастся! Для программирования Ардуино предусмотрите возможность отключения питания Bluetooth модуля, например отключения линии 5 V. После загрузки прошивки и отключения от USB, питание модуля можно включить, а к Ардуино подключить питание от батареи.

Схема соединения Bluetooth модуля с Ардуино

Подключение:

  • Управлять Bluetooth модулем HC-05 можно либо с компьютера, либо через микроконтроллер, например, Arduino. Вывод RX модуля подключается к выводу TX, а вывод TX модуля подключается к выводу RX того устройства с которого он будет управляться.
  • Для подключения модуля к компьютеру (без микроконтроллеров) потребуется адаптер USB-UART, или адаптер RS232-UART, или программатор с выводами TX RX, вместо адаптера USB-UART можно использовать плату Arduino, как описано в статье Wiki — используем Arduino как USB — UART преобразователь. Для отправки команд в модуль потребуется установить программу терминал. Одним из таких терминалов является свободно распространяемая программа Termite с поддержкой Русского языка.
  • Для подключения модуля к Arduino можно воспользоваться аппаратной или программной шиной UART. При использовании аппаратной шины, модуль подключается к выводам TX и RX указанным на плате. При использовании программной шины, модуль подключается к назначаемым выводам TX и RX Arduino.

Проверка:

После каждого подключения питания или перезагрузки модуля, до того как отправлять команды, нужно кратковременно нажать на кнопку модуля. Если у модуля нет кнопки, то кратковременно подать высокий уровень на вывод K. После чего модуль останется в обычном режиме, но будет воспринимать AT-команды. Помимо обычного режима, модуль может работать в режиме AT-команд. О том как войти в этот режим и чем он отличается от обычного, рассказано ниже, в разделе примечание.

Для проверки связи с Bluetooth модулем отправьте тестовую команду AT (введите текст AT и нажмите Enter). Если связь установлена корректно, то модуль ответит OK. После этого можно отправлять остальные AT-команды.

Connecting the Smartphone to the HC-05 Bluetooth Module and the Arduino

Now we are ready to connect the smartphone to the Bluetooth module and the Arduino. What we need to do here is to activate the Bluetooth and the smartphone will find the HC-05 Bluetooth module.

Then we need to pair the devices and the default password of the HC-05 module is 1234. After we have paired the devices we need an application for controlling the Arduino. There are many application in the Play Store for this purpose which will work with the Arduino code that we wrote. However, I made my own custom application for this tutorial using the MIT App Inventor online application. This is a great and easy to use application for building Android application and in my next tutorial you can find a detailed step by step guide how to build your own custom Android application for your Arduino Project.

You can download the app that I made for this example here:

Arduino Bluetooth Tutorial Example Android App

1 file(s) 1.38 MB

With the connect button we will connect the smartphone to the Bluetooth module and the status text below the button will tell us whether we have successfully connected. Using the “Turn ON” and “Turn OFF” buttons we can turn on and off the LED. The text above the buttons is the one that the Arduino is sending back to the smartphone when a particular button is pressed.

Создание проекта для ATmega8 в программной среде CodeVision

Аналогичные операции можно произвести и в других программных средах для программирования микроконтроллеров AVR, например, Atmel Studio.

После установки CodeVision вам необходимо выполнить следующие ниже перечисленные шаги чтобы создать проект и написать программу.

Шаг 1. Создайте новый проект в CodeVision, выбрав пункт меню File -> New -> Project. В появившемся диалогом окне нажмите Yes.

Шаг 2. Откроется CodeWizard. Кликните в ней на первой опции, то есть AT90, затем нажмите OK.

Шаг 3. Выберите свой микроконтроллер, в нашем случае им будет Atmega8.

Шаг 4. Кликните на Ports (порты). В нашем проекте мы будем использовать Port C4 и C5 для управления светодиодом. Таким образом, необходимо сконфигурировать биты 4 и 5 как выходные кликнув на них, как показано на рисунке:

Шаг 5. Мы будем использовать универсальный асинхронный последовательный приемопередатчик (USART) для Rx и Tx (приема и передачи данных). Поэтому необходимо выбрать настройки USART, в них кликнуть на настройки приема и оставить их по умолчанию.

Шаг 6. Выберите Program -> Generate, Save and Exit. Теперь более половины вашей работы по программированию микроконтроллера Atmega8 можно считать выполненной.

Шаг 7. Создайте новую папку на рабочем столе чтобы записывать туда наши файлы.

У нас будет 3 диалоговых окна (будут появляться последовательно одно за другим) для сохранения наших файлов.

Сделайте то же самое (что и на представленном рисунке) с двумя другими диалоговыми окнами – то есть сохраните предлагаемые ими файлы.

После этого рабочая область программы будет выглядеть следующим образом:

Теперь большая часть работы по программированию микроконтроллера Atmega8 нами выполнена с использованием такой удобной программной среды как CodeVision. Но ели вы не хотите использовать данную программную среду, то вы можете запрограммировать работу с последовательным портом микроконтроллера вручную по аналогии с последовательностью действий в таких статьях на нашем сайте как:

  • взаимодействие двух микроконтроллеров AVR ATmega8 через UART;
  • связь AVR ATmega8 и Arduino Uno через универсальный асинхронный приемопередатчик (UART)

Connecting To A Computer

Please note that I am a Windows user so all examples use a Windows system.

There are a couple of ways you can connect the serial Bluetooth modules to a computer; either via a serial UART to usb adapter, or with an Arduino + serial in – serial out sketch (or any other similar microprocessor). I tend to use an Arduino.

I have a few slightly different sketches but I start with a very basic one. This takes wha ever you enter in the serial monitor and sends it to the connected module. Anything it receives from the module it displays in the serial monitor main window.

Basic Serial Communication Sketch

Hardware serial is used to talk to the host computer/Arduino serial monitor and AltSoftSerial is used to talk to the Bluetooth module. The sketch can be used to talk to any module that uses serial communication.

The sketch can be used to talk to any module that uses serial communication.

//  Basic serial communication sketch using AltSoftSerial (ASS). 
//  Uses hardware serial to talk to the host computer and ASS for communication with the Bluetooth module
//
//  When a command is entered in the serial monitor on the computer 
//  the Arduino will relay it to the Bluetooth module and display the result in the serial monitor.
//
//  Pins
//  BT VCC to Arduino 5V out. 
//  BT GND to GND
//  Arduino D8 ASS RX - BT TX no need voltage divider 
//  Arduino D9 ASS TX - BT TX through a voltage divider
//
 
#include <AltSoftSerial.h>
AltSoftSerial BTSerial; 
 
char c=' ';
boolean NL = true;
 
void setup() 
{
    Serial.begin(9600);
    Serial.print("Sketch:   ");   Serial.println(__FILE__);
    Serial.print("Uploaded: ");   Serial.println(__DATE__);
    Serial.println(" ");
 
    BTSerial.begin(9600);  
    Serial.println("BTserial started at 9600");
 
    // If using an HC-05 in AT command mode the baud rate is likely to be 38400
    // Comment out the above 2 lines and uncomment the following 2 lines. 
    // BTSerial.begin(38400); 
    // Serial.println("BTserial started at 38400");
 
    Serial.println("");
 
}
 
void loop()
{
 
    // Read from the Bluetooth module and send to the Arduino Serial Monitor
    if (BTSerial.available())
    {
        c = BTSerial.read();
        Serial.write(c);
    }
 
 
    // Read from the Serial Monitor and send to the Bluetooth module
    if (Serial.available())
    {
        c = Serial.read();
        BTSerial.write(c);   
 
        // Echo the user input to the main window. The ">" character indicates the user entered text.
        if (NL) { Serial.print(">");  NL = false; }
        Serial.write(c);
        if (c==10) { NL = true; }
    }
 
}

Connections

All modules are connected in a similar way.
vcc to 5V
GND to GND
TX to Arduino RX (pin D8 when using AltSoftSerial)
RX to voltage divider then to Arduino TX (pin D9 when using AltSoftSerial)

On some modules like the HM-10, the pin order may be reversed. Just make sure the above connections are used.

Trouble Shooting

If you can’t get communication with the Arduino working, try the following:
1 – Check your connections. Make sure you have Arduino TX to BT RX and Arduino RX to BT TX.
2 – Check the value of the resistors.
3 – Check that the resistors are in the correct order (the 1K ohm resistor connects to the Arduino).
4 – Different baud rates. Not all modules use 9600 as the default.
5 – Change the line endings (\r\n). Some modules need them, other don’t.
6 – Try upper and lower case.
7 – Check your connections.

HC-05 zs-040 hc01.com V2.1

Another version of the HC-05 on the zs-040 breakout board but this ones uses the real HC SMD Bluetooth board (you can tell by the logo and the blue LED).

The hardware is basically the same as the HC-06. The difference is the firmware. The HC-05s can operate as MASTER or SLAVE devices.

These start in communication mode and need to be put in to AT mode by bringing pin 34 HIGH. This can be done by closing the small button switch as you power the modules. When in AT mode the baud rate is set to 38400.
Unlike the other zs-040 HC-05 modules I have it looks like bringing pin 34 HIGH after the modules have started does not put them in AT mode. I haven’t really investigated this properly though.

Uses the CSR BC04 (BC417) chip
Bluetooth version v2.0 + EDR
Firmware hc01.comV2.1. by Wavesen.
Default communication baud rate is 9600
AT mode baud rate is 38400
Default PIN is 1234
Default name is HC-05
The small Bluetooth boards have a blue LED at the top left.

The EN pin when briefly brought LOW, breaks an active connection and resets the module.
The STATE pin goes HIGH when a connection is made.

AT commands require the nl/cr line endings and can be in upper case or lower case.

Downloads

Chinese data sheetEnglish data sheetChinese AT command guideEnglish AT command guide

As with the HC-06s the Chinese data sheets are more up-to-date than the English ones.

Further Information

Guangzhou HC website (Chinese only but google translate works)Website download page (Chinese only again). Note the English docs are not as up-to-date as the Chinese docs.Wavesen product page.Only the first photo shows the the correct (with LED) version. The other photos still show the the older no blue LED version.

Step 5: AT Commands

For HC05: Type «AT» (without the quotes) on the serial monitor and press enter. if «OK» appears then everything is all right and the module is ready to take command. Now you can change the name of the module, retrieve address or version or even reset to factory settings. To see the default name, type AT+NAME. The name will be prompted, by default it is HC-05 or JY_MCU or something like that. To change the name just type AT+NAME=your desired name.

Here is an important note, if the key pin is not high, i.e. not connected to Vcc while receiving AT commands(if you did not solder the wire and released it after the module entered AT mode), it will not show the default name even after giving right command. But you can still change the name by the command mentioned above. To verify if the name has really changed, search the device from your pc/mobile. The changed name will appear. To change baud rate, type AT+UART=desired baud rate. Exit by sending AT+RESET command.

Most useful AT commands are

AT : Ceck the connection.AT+NAME : See default nameAT+ADDR : see default addressAT+VERSION : See versionAT+UART : See baudrateAT+ROLE: See role of bt module(1=master/0=slave)AT+RESET : Reset and exit AT modeAT+ORGL : Restore factory settingsAT+PSWD: see default password

More detailed AT commands are given in the 1st pdf.

For HC06: On arduino serial monitor type «AT» (without the quotes) and press enter, «OK» will confirm AT mode. Unlike HC05, you can’t see the default name or baud rate. You can only change them. To change name type AT+NAMEDESIRED NAME, notice that there should be no space between the command and name. The module will reply OKyour set name. For example, AT+NAMEPROTOTYPE will set the name to PROTOTYPE. To change baud rate, type AT+BAUDX, where X=1 to 9.

1 set to 1200bps2 set to 2400bps 3 set to 4800bps 4 set to 9600bps (Default) 5 set to 19200bps 6 set to 38400bps 7 set to 57600bps 8 set to 115200bpsso sending AT+BAUD4 will set the baud rate to 9600.

For Tera Term write down the commands somewhere else and paste it on the console by right clicking. No need of pressing enter. The command will be executed immediately and confirmed.

HC 06 AT commands are limited, all I could find are given here.

AT : check the connectionAT+NAME: Change name. No space between name and command.AT+BAUD: change baud rate, x is baud rate code, no space between command and code.AT+PIN: change pin, xxxx is the pin, again, no space.AT+VERSION

More details in 2nd pdf.

Attachments

  • HC-0305 serail module AT commamd set 201104 revised_2.pdfDownload
  • EGBT-045MS-046S Bluetooth Module Manual rev 1r0.pdfDownload

Bluetooth в Arduino проектах

Самыми популярными модулями являются устройства на основе чипа BC417. Эта серия называется HC. Модули HC-03 и HC-05 могут быть и сервером соединения, и клиентом, они обладают широким набором АТ команд.

Для подключения к ПК потребуются модуль Bluetooth, плата Ардуино, соединительные провода и компьютер. Скетч для управления платой Ардуино через смартфон и компьютер будет одинаковым, так как в обоих случаях данные в микроконтроллер буду поступать по протоколу UART. Схема подключения Bluetooth-модуля к плате представлена на рисунке. Пин RX на ардуино подключается к TDX, TX – к RDX, GND – к GND, 5V – к VCC.

При загрузке скетча нужно отключить Bluetooth-модуль, иначе будет появляться ошибка доступа к Ардуино.  Также нужно установить на смартфон или планшет, поддерживающий ОС Android, приложение для отправки данных на модуль.  После установки приложения нужно загрузить скетч и подключить модуль к плате Ардуино.  Пример кода мигания светодиода:


int val;

void setup()

{

Serial.begin(9600);

pinMode(13, OUTPUT); // 13 пин – светодиод, объявляется как выход

}

void loop()

{

if (Serial.available()) // проверка поданных команд

{

val = Serial.read();

if (val == '1') {digitalWrite(13, HIGH);} // при 1 включается светодиод

if (val == '0') {digitalWrite(13, LOW);}  // при 0 выключается светодиод

}

}

Теперь нужно настроить соединение телефона и модуля. Для установки соединения нужно зайти в настройки телефона и включить Bluetooth. Как только устройство будет найдено, нужно ввести пароль – обычно это «1234» или «0000». После этого нужно зайти в приложение, нажать на кнопку «подключить Bluetooth» и выбрать нужное устройство. При успешном сопряжении на модуле светодиод начнет мигать медленнее,  примерно 1 раз в 2 секунды.

В скетче светодиод включается и выключается при получении цифр «1» и «0». Кроме цифр также можно использовать буквы латинского алфавита с учетом регистра.

Аналогичным образом можно подключаться к модулю при помощи компьютера. Для этого существуют различные программы, которые подключатся к COM-порту. При запуске программы запрашивают номер порта, скорость  и тип подключения. При успешном подключении на экране появится поле терминала, в которое нужно ввести с клавиатуры цифры/буквы, включающие светодиод.

Code

This is probably the simplest code to test all the device that support the serial port communication. It simply connects the computer terminal and the HC-05 in a loop. The codes sends the messages from the terminal to the Bluetooth Module and messages from the Bluetooth module to the terminal.

#include <SoftwareSerial.h>
SoftwareSerial EEBlue(10, 11); // RX | TX
void setup()
{
 
  Serial.begin(9600);
  EEBlue.begin(9600);  //Default Baud for comm, it may be different for your Module. 
  Serial.println("The bluetooth gates are open.\n Connect to HC-05 from any other bluetooth device with 1234 as pairing key!.");
 
}
 
void loop()
{
 
  // Feed any data from bluetooth to Terminal.
  if (EEBlue.available())
    Serial.write(EEBlue.read());
 
  // Feed all data from termial to bluetooth
  if (Serial.available())
    EEBlue.write(Serial.read());
}

Test The Connection

On the HC-05, remove the connection to pin 34 and upload the following sketch to the Arduino connected to it. The sketch opens the BTserial at 9600 for communication mode.

// Basic Bluetooth sketch HC-05_03_9600
// Connect the HC-05 module and communicate using the serial monitor
//
// The HC-05 defaults to commincation mode when first powered on.
// Needs to be placed in to AT mode
// After a factory reset the default baud rate for communication mode is 38400
//
//
//  Pins
//  BT VCC to Arduino 5V out. 
//  BT GND to GND
//  BT RX to Arduino pin 3 (through a voltage divider)
//  BT TX to Arduino pin 2 (no need voltage divider)
 
 
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX. 
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.
 
char c = ' ';
 
void setup() 
{
    // start the serial communication with the host computer
    Serial.begin(9600);
    Serial.println("Arduino with HC-05 is ready");
 
    // start communication with the HC-05 using 9600
    BTserial.begin(9600);  
    Serial.println("BTserial started at 9600");
}
 
void loop()
{
 
     // Keep reading from HC-05 and send to Arduino Serial Monitor
    if (BTserial.available())
    {  
        c = BTserial.read();
        Serial.write(c);
    }
 
    // Keep reading from Arduino Serial Monitor and send to HC-05
    if (Serial.available())
    {
        c =  Serial.read();
        BTserial.write(c);  
    }
 
}

Reset both Arduinos and remove power from the HC-05 and the HC-06

Power on the HC-06. The LED should be rapidly blinking 5 times per second. This indicates it is waiting for a connection or to be paired.
Power on the HC-05. The LED will blink a couple of times when first on and then change to a the regular pattern of blinking quickly every couple of seconds.
The LED on the HC-06 will turn on full time (no blinking).
The modules are now connected.

Open the serial monitors and what ever you enter in one will appear the the other and visa versa

Every time the modules are powered on they should connect. If you find they do not connect then cycle the power to the Arduinos. Sometimes the HC-05 will get stuck trying to make a connection. In this case the LED on the HC-05 will either
1. quickly blink 3 times every couple of seconds.
2. blink on/off twice a second.
This normally happens when the HC-06 is turned off and then back on again without resetting the HC-05.

The devices seem to connect more quickly when the HC-06 is started first.

HC-06 zs-040 hc01.com v2.0

These look like the common HC-05/HC-06 on the zs-040 breakout boards but have a different firmware.

These use the genuine HC SMD Bluetooth module and (at the time of writing) have the latest HC firmware

The modules here were sold as HC-06s and do not have STATE pins or EN pins.

Uses the CSR BC04 (BC417) chip
Bluetooth version v2.0 + EDR
Firmware hc01.comV2.0. The firmware is SLAVE only version by Wavesen
Default baud rate is 9600
Default PIN is 1234
Default name is HC-06
The small Bluetooth boards have a blue LED at the top left.

AT commands are required to be in upper case and nl/cr line endings not required.

AT+LED turns off the on board LED. This is the blue LED on the small daughter board not the red LED on the larger breakout board. I originally though the 2 LEDs were linked but if you turn off the blue LED the red LED keeps flashing.

AT+LED0 – turn off the blue LED, returns LED ON
AT+LED1 – turn on the blue LED, returns LED ON

Other commands can be found in the data sheet.

Interesting there is a ROLE command;
AT+ROLE=S puts the module in to SLAVE mode, returns OK+ROLE:S
AT+ROLE=M puts the module in to MASTER mode, returns OK+ROLE:M
The commands are accepted and I originally thought this may mean the modules can be used as HC-05s but I cannot get any of the usual HC-05 commands to work; ROLE, AT+ROLE, AT+ROLE=, AT+ROLE? doesn’t work for example.

Downloads

Chinese Data SheetEnglish Data Sheet.Data sheet for the 1.8 firmware but the commands seem to be the same.

The modules I have match the photo in the Chinese data sheet. The photo in the English data sheet would appear to be an older version.

Further Information

Guangzhou HC website (Chinese only but google translate works)Website download page (Chinese only again). Note the English docs are not as up-to-date as the Chinese docs.Wavesen product page.This shows the older no blue LED version. Wavesen and HC01 are the same company.

HC-06 Set Up

Build the HC-06 circuit, power on and load the following sketch. My HC-06 is set to use 9600 baud rate. If yours is using a different speed then you will need to change the sketch. Change the following lines:
BTSerial.begin(9600);
Serial.println(“BTserial started at 9600”);
Change the 9600 to what ever speed your HC-06 is using.

// Basic bluetooth test sketch. HC-06_01_9600
// HC-06 ZS-040 
// 
// 
//  Uses hardware serial to talk to the host computer and software serial for communication with the bluetooth module
//
//  Pins
//  BT VCC to Arduino 5V out. 
//  BT GND to GND
//  BT RX to Arduino pin 3 (through a voltage divider)
//  BT TX to Arduino pin 2 (no need voltage divider)
//
//  When a command is entered in the serial monitor on the computer 
//  the Arduino will relay it to the bluetooth module and display the result.
//
//  These HC-06 modules require capital letters and no line ending
//
 
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(2, 3); // RX | TX
 
void setup() 
{
    Serial.begin(9600);
    Serial.println("Arduino with HC-06 is ready");
 
    // HC-06 default baud rate is 9600
    BTSerial.begin(9600);  
    Serial.println("BTserial started at 9600");
}
 
void loop()
{
 
  // Keep reading from HC-06 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());
 
  // Keep reading from Arduino Serial Monitor and send to HC-06
  if (Serial.available())
  BTSerial.write(Serial.read());
}

HC-06 modules start in AT mode so we can start entering commands as soon as we open the serial monitor. Remember that the HC-06 requires commands to be upper case and does not want new lines or carriage returns so set “No line endings” at the bottom of the serial monitor window. Open the serial monitor on the host computer and confirm you are in AT mode by typing “AT” (no quotes). You should get a reply of “OK”

We don’t need to do much to prepare the HC-06. Just make sure the password is the same as the HC-05.
To change the password/PIN to 1234 enter “AT+PSWD1234” (no quotes) and click Send

Arduino Source Codes

Description: So first we need to define the pins and some variables needed for the program. In the setup section, at the master, we set the LED pin as output and set it low right away, as well as, start the serial communication at 38400 baud rate. Similar, at the slave, we set the button pin as input, define the servo to which pin is connected and start the serial communication with the same baud rate.

In the loop section, in both code, with the Serial.available() function we will check whether there is available data in the serial port to be read and using the Serial.read() function we will read and store the data into the “state” variable. So if the master receive the character ‘1’ which is sent from the slave when the button state is high, or the button is pressed, the LED will be on. Else if the character is ‘0’ the LED will be off.

As for the servo motor control, first at the master, we read the potentiometer value and map it into a suitable range for the servo from 0 to 255. This value is sent to the slave which use it to rotate the servo motor accordingly. That’s all we need and here’s the demonstration of the example.

Master Code:

/*
 * How to configure and pair two HC-05 Bluetooth Modules
 * by Dejan Nedelkovski, www.HowToMechatronics.com
 * 
 *                 == MASTER CODE ==
 */

#define ledPin 9

int state = 0;
int potValue = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(38400); // Default communication rate of the Bluetooth module
}

void loop() {
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
 }
 // Controlling the LED
 if (state == '1') {
  digitalWrite(ledPin, HIGH); // LED ON
  state = 0;
 }
 else if (state == '0') {
  digitalWrite(ledPin, LOW); // LED ON
  state = 0;
 }
 // Reading the potentiometer
 potValue = analogRead(A0);
 int potValueMapped = map(potValue, 0, 1023, 0, 255);
 Serial.write(potValueMapped); // Sends potValue to servo motor
 delay(10);
}

Slave Code:

/*
 * How to configure and pair two HC-05 Bluetooth Modules
 * by Dejan Nedelkovski, www.HowToMechatronics.com
 * 
 *                 == SLAVE CODE ==
 */
 
#include <Servo.h>
#define button 8

Servo myServo;
int state = 20;
int buttonState = 0;

void setup() {
  pinMode(button, INPUT);
  myServo.attach(9);
  Serial.begin(38400); // Default communication rate of the Bluetooth module
}

void loop() {
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
 }
 // Controlling the servo motor
 myServo.write(state);
 delay(10);
 
 // Reading the button
 buttonState = digitalRead(button);
 if (buttonState == HIGH) {
   Serial.write('1'); // Sends '1' to the master to turn on LED
 }
 else {
   Serial.write('0');
 }  
}

That’s all and if you have any problems, feel free to ask for help in the comments section below.