HC-06 Bluetooth chat on an Arduino Uno
An HC-06 on SoftwareSerial at 9600. Pair from the Bluetooth tab with PIN 1234, connect, and send 1 or 0 for the LED. Simulated Bluetooth, no radio. The whole build, an Arduino Uno and 1 more part, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The parts retail for about $34. On Mokxi they're free.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// HC-06 Bluetooth chat: the four-pin module on a SoftwareSerial port.
//
// HC-06 TXD -> pin 2 (the sketch's RX)
// HC-06 RXD <- pin 3 (the sketch's TX)
// HC-06 VCC -> 5V, GND -> GND
//
// Simulated Bluetooth: a phone in Mokxi, not a real radio. Press Run, open
// the Bluetooth tab, pair with the HC-06 (PIN 1234) and connect, the way a
// phone's terminal app does. Then send 1 or 0 and the LED on pin 13 follows.
//
// An HC-06 comes out of the bag with nothing connected, and until something
// connects, whatever the sketch sends it is an AT command: the hello below
// is only sent once a phone is there to read it.
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(2, 3); // RX, TX
char line[32];
byte length = 0;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
BTSerial.begin(9600);
Serial.println("HC-06 chat ready at 9600 baud. Connect from the Bluetooth tab.");
}
// A whole line from the phone. The answer waits until the line has ended:
// SoftwareSerial cannot listen while it talks.
void command() {
line[length] = '\0';
if (strcmp(line, "1") == 0) {
digitalWrite(LED_BUILTIN, HIGH);
BTSerial.println("LED on");
} else if (strcmp(line, "0") == 0) {
digitalWrite(LED_BUILTIN, LOW);
BTSerial.println("LED off");
} else {
BTSerial.println("Send 1 or 0 for the LED.");
}
length = 0;
}
void loop() {
if (BTSerial.available()) {
char c = BTSerial.read();
Serial.write(c);
if (c == '\n') {
command();
} else if (c != '\r' && length < sizeof(line) - 1) {
line[length++] = c;
}
}
}
Parts list
3 parts, plus the jumper wires. They retail for about $34; on Mokxi they're free.
How it is wired
4 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Arduino Uno R3 pin 3; Bluetooth serial module, HC-06 pin RXD
- Arduino Uno R3 pin 2; Bluetooth serial module, HC-06 pin TXD
- Arduino Uno R3 pin 5V; Bluetooth serial module, HC-06 pin VCC
- Ground: Arduino Uno R3 pin GND; Bluetooth serial module, HC-06 pin GND
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.