Try Embedded

Bluetooth remote control (HC-05)

Switch an LED and read a sensor from a phone through an HC-05 Bluetooth module.

Communication · Beginner

In a real product: Bluetooth-controlled lamp (Smart home): A phone app switches the lamp and reads its sensor.

An HC-05 is a wireless serial cable: whatever the phone sends comes out of the module's TXD pin, and whatever the board sends to RXD appears on the phone. A few text commands are enough to control a board from a phone app.

What you'll learn

  • Talking to a Bluetooth module over SoftwareSerial
  • Reading text commands one line at a time
  • Answering with sensor readings

How it works

The module's TXD goes to pin 10 and RXD to pin 11, and SoftwareSerial uses those as a second serial port at 9600 baud. The sketch collects characters until a newline, then acts on the line: ON and OFF switch the LED, READ sends the potentiometer's value back to the phone.

On a real 5 V board, put a voltage divider (1 kΩ and 2 kΩ) on the line into RXD: the module's inputs are 3.3 V.

Try this

  • Run it, select the module and type ON, OFF or READ in the box under it: that is the phone sending a line. The phone's replies show under the box.
  • Add a BLINK command that blinks the LED until the next command.
  • Send the reading every second without being asked, as a telemetry stream.

sketch.ino

// Commands from a phone through an HC-05 (TXD to 10, RXD to 11): ON, OFF and READ. LED on 13, knob on A0.
#include <SoftwareSerial.h>

SoftwareSerial bt(10, 11);   // RX, TX
const int LED = 13, KNOB = A0;
String line;

void handle(String cmd) {
  cmd.trim();
  cmd.toUpperCase();
  if (cmd == "ON") { digitalWrite(LED, HIGH); bt.println("LED on"); }
  else if (cmd == "OFF") { digitalWrite(LED, LOW); bt.println("LED off"); }
  else if (cmd == "READ") { bt.print("Knob: "); bt.println(analogRead(KNOB)); }
  else { bt.print("Unknown command: "); bt.println(cmd); }
  Serial.print("Phone sent: ");
  Serial.println(cmd);
}

void setup() {
  Serial.begin(9600);
  bt.begin(9600);
  pinMode(LED, OUTPUT);
  bt.println("Hello from the Arduino. Commands: ON, OFF, READ");
}

void loop() {
  while (bt.available()) {
    char c = bt.read();
    if (c == '\n') { handle(line); line = ""; }
    else if (line.length() < 32) line += c;
  }
}

Lessons behind it