Arduino bluetooth hc 05 master slave

Arduino bluetooth hc 05 master slave

Для настройки Bluetooth модулей HC-05 загрузите этот скетч на плату.

//Начало скетча Копировать этот код

//Начало скетча #include SoftwareSerial.h> // имя пароль скорость CMODE получить адрес записать адрес роль //запрос AT+NAME? AT+PSWD? AT+UART? AT+CMODE? AT+ADDR? AT+BIND? AT+ROLE? //вариант ответа +NAME:SLAVE +PIN:"1234" +UART:9600,0,0 +CMODE:1 AT+BIND=18,E4,400006 +ROLE:0 //-------------------------------------------------------------------------------------------------------------------------------------------------- //какие установить (более подробно смотрите видео которое внизу статьи) //для слейва | AT+NAME=SLAVE AT+PSWD="1234" AT+UART=9600,0,0 AT+CMODE=1 +ADDR:18:E4:400006 AT+ROLE=0 //для мастера | AT+NAME=MASTER AT+PSWD="1234" AT+UART=9600,0,0 AT+CMODE=0 AT+BIND=18,E4,400006 AT+ROLE=1 //сброс настроек AT+ORGL это для крайнего случая, если что то напутали с настройками, и не можете найти как исправить const int arduino_rx = 5; const int arduino_tx = 6; SoftwareSerial mySerial (arduino_rx, arduino_tx); void setup()  pinMode( arduino_rx,INPUT); pinMode( arduino_tx,OUTPUT); Serial.begin(9600); //в мониторе порта выбрать NL&CR, скорость Arduino с компьютером 9600 mySerial.begin(38400); //по умолчанию скорость Bluetooth модуля с Arduino в режиме AT команд 38400 иногда 9600 Serial.println( ">>"); mySerial.println("AT"); > void loop()  if (mySerial.available())  char c = mySerial.read(); // читаем из программного Serial-порта Serial.print(c); > // пишем в штатный Serial-порт if (Serial.available())  char c = Serial.read(); // читаем из штатного Serial-порта mySerial.write(c); > // пишем в программный Serial-порт > //конец скетча 

После загрузки скетча соберите все, как показано на этой схеме.

И следуйте инструкциям на видео, которое я оставил в конце этой статьи.

Ниже представлены два скетча для взаимодействия двух плат Arduino с применение Bluetooth модулей HC-05.

Скетч для платы Arduino Nano (с кнопкой)

//Начало скетча Копировать этот код

const int button = 2; int button_state = 0; void setup()  pinMode( button,INPUT_PULLUP); Serial.begin(9600); > void loop()  button_state = digitalRead(button); if (button_state == LOW) Serial.print("1"); > if (button_state == HIGH) Serial.print("0"); > > 

Скетч для платы Arduino Uno которая будет включать светодиод

//Начало скетча Копировать этот код

const int led_Pin = 13; void setup()  pinMode( led_Pin,OUTPUT); Serial.begin(9600); > void loop()  if (Serial.available())  char c = Serial.read(); if (c == '1') digitalWrite(led_Pin, HIGH);> if (c == '0') digitalWrite(led_Pin, LOW);> > > 

После загрузки скетчей соберите все, как показано на этой схеме.

Если все верно, то подключаем питание и проверяем нажатием кнопки. Более подробно, смотрите видео, которое ниже.

Источник

How To Configure and Pair Two HC-05 Bluetooth Modules as Master and Slave | AT Commands

In this Arduino Tutorial we will learn how to configure and pair two HC-05 Bluetooth Modules as Master and Slave devices.You can watch the following video or read the written tutorial below.

How To Configure and Pair Two HC-05 Bluetooth Module as Master and Slave AT Commands

So the RX pin of the Arduino needs to be connected to the RX pin of the Bluetooth module, through the voltage divider, and the TX pin of the Arduino to the TX pin of the Bluetooth module. Now while holding the small button over the “EN” pin we need to power the module and that’s how we will enter the command mode. If the Bluetooth module led is flashing every 2 seconds that means that we have successfully entered in the AT command mode.

After this we need to upload an empty sketch to the Arduino but don’t forget to disconnect the RX and TX lines while uploading. Then we need to run the Serial Monitor and there select “Both NL and CR”, as well as, “38400 baud” rate which is the default baud rate of the Bluetooth module. Now we are ready to send commands and their format is as following.

AT Commands Format

All commands start with “AT”, followed by the “+” sign, then a and they end either with the “?” sign which returns the current value of the parameter or the “=” sign when we want to enter a new value for that parameter.

Slave Configuration

So for example, if we type just “AT” which is a test command we should get back the message “OK”. Then if we type “AT+UART?” we should get back the massage that shows the default baud rate which is 38400. Then if we type “AT+ROLE?” we will get back a massage “+ROLE=0” which means that the Bluetooth device is in slave mode. If we type “AT+ADDR?” we will get back the address of the Bluetooth module and it should looks something like this: 98d3:34:905d3f.

Slave Configuration HC-05 Bluetooth Module Arduino

Now we need to write down this address as we will need it when configuring the master device. Actually that’s all we need when configuring the slave device, to get its address, although we can change many different parameters like its name, baud rate, pairing password and so on, but we won’t do that for this example.

Master Configuration

Ok now let’s move on and configure the other Bluetooth module as a master device. First we will check the baud rate to make sure it’s the same 38400 as the slave device. Then by typing “AT+ROLE=1” we will set the Bluetooth module as a master device. After this using the “AT+CMODE=0” we will set the connect mode to “fixed address” and using the “AT+BIND=” command we will set the address of the slave device that we previously wrote down.

Master Configuration HC-05 Bluetooth Module Arduino

Note here that when writing the address we need to use commas instead of colons. Also note that we could have skipped the previous step if we entered “1” instead of “0” at the “AT+CMODE” command, which makes the master to connect to any device in its transmission range but that’s less secure configuration. Here you can find a complete list of commands and parameters: HC-05 AT Commands List

Nevertheless, that’s all we need for a basic configuration of the Bluetooth modules to work as a master and slave devices and now if we reconnect them in normal, data mode, and re-power the modules, in a matter of seconds the master will connect to the slave. Both modules will start flashing every 2 seconds indicating a successful connection.

Communication Between Two HC-05 Bluetooth Module Example

Ok so now we are ready make the practical example for this tutorial. Here’s the circuit schematics. We will use a potentiometer, at the master, to control a servo motor at the slave. And vice versa, we will use a push button, at the slave, to control a LED at the master.

Communcation Between Two HC-05 Bluetooth Module Circuit Schematics

You can get the components needed for this Arduino tutorial from any of the sites below:

  • HC-05 Bluetooth Module ……………. Amazon / Banggood / AliExpress
  • Arduino Board …………………………… Amazon / Banggood / AliExpress
  • Servo Motor…………………………….…. Amazon / Banggood / AliExpress
  • Potentiometer……………..………..……. Amazon / Banggood / AliExpress
  • 3x 220 Ohms resistors………………… Amazon / Banggood / AliExpress
  • Breadboard and Jump Wires ………. Amazon / Banggood / AliExpress

Disclosure: These are affiliate links. As an Amazon Associate I earn from qualifying purchases.

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); >Code language: Arduino (arduino)
/* * How to configure and pair two HC-05 Bluetooth Modules * by Dejan Nedelkovski, www.HowToMechatronics.com * * == SLAVE CODE == */ #include #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'); > >Code language: Arduino (arduino)

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

Источник

Читайте также:  Motor shield l293d bluetooth
Оцените статью
Adblock
detector