Last active
November 18, 2018 23:48
-
-
Save aelse/4887b09598264d39bf27851c2613ff52 to your computer and use it in GitHub Desktop.
Arduino hc_05 command mode - for controlling and configuring bluetooth module via arduino
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* hc_05_command_mode.ino | |
* | |
* Copyright 2018 Alexander Else (github @aelse). | |
* Released under MIT License. | |
* | |
* Use 'COMMAND' to enter command mode and send AT commands to HC-05 module. | |
* Use 'DATA' to enter data mode for normal use (including pairing). | |
*/ | |
#include <SoftwareSerial.h> | |
// Soft power switch to HC-05 module. A transistor between GND pin on HC-05 and ground on Arduino. | |
#define HC_05_PWR_SW 8 | |
// EN sometimes labelled KEY on HC-05. | |
#define HC_05_EN 9 | |
#define HC_05_TX 10 | |
#define HC_05_RX 11 | |
SoftwareSerial BTSerial(HC_05_TX, HC_05_RX); // RX | TX : reversed relative to HC-05 module | |
// Sets value to EN pin and power cycles the HC-05 module. | |
// HIGH enables command mode. LOW enables data mode. | |
void hc05SetModeReboot(uint8_t v) { | |
digitalWrite(HC_05_EN, v); | |
// Cycle relay | |
digitalWrite(HC_05_PWR_SW, LOW); | |
delay(10); | |
digitalWrite(HC_05_PWR_SW, HIGH); | |
} | |
void setup() | |
{ | |
pinMode(HC_05_EN, OUTPUT); | |
digitalWrite(HC_05_EN, HIGH); | |
pinMode(HC_05_PWR_SW, OUTPUT); | |
hc05SetModeReboot(HIGH); // Start up in command mode. | |
Serial.begin(9600); | |
Serial.setTimeout(10); // readString timeout | |
BTSerial.begin(38400); // HC-05 factory default (some modules come preconfigured 9600 bps) | |
Serial.println("Entered command mode. Ready for AT commands:"); | |
} | |
void loop() | |
{ | |
// Keep reading from HC-05 and send to Arduino Serial Monitor | |
while (BTSerial.available()) | |
Serial.write(BTSerial.read()); | |
// Keep reading from Arduino Serial Monitor and send to HC-05 | |
while (Serial.available()) { | |
auto s = Serial.readString(); | |
if (s.startsWith("DATA")) { | |
hc05SetModeReboot(LOW); | |
Serial.println("Entered data mode."); | |
} else if (s.startsWith("COMMAND")) { | |
hc05SetModeReboot(HIGH); | |
Serial.println("Entered command mode."); | |
} else { | |
BTSerial.write(s.c_str()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment