Control a Relay with ESP32 via Bluetooth Using MIT App Inventor _Part 2
Welcome to Part 2 of our Smart Relay series. In Part 1, we handled the physical wiring. Now, we bring the hardware to life by programming the ESP32.
In this tutorial, we will write a C++ sketch using the Arduino IDE that turns the ESP32 into a Bluetooth Classic device, capable of receiving serial data strings from any smartphone.
Step 1: Understanding the Hardware Logic
Before coding, ensure you know which GPIO pin connects to your relay. In our example, we use GPIO 23.
The ESP32 has built-in Bluetooth and Wi-Fi, making it superior to the older Arduino UNO + HC-05 combination. We will use the Bluetooth Classic protocol (via the BluetoothSerial.h library) because it is simpler to implement for beginner projects than BLE.
Step 2: The ESP32 Firmware
Copy the following code into your Arduino IDE. This sketch initializes the Bluetooth radio and listens for incoming characters ('1' for ON, '0' for OFF).
#include "BluetoothSerial.h" // Native library for ESP32
BluetoothSerial SerialBT;
const int relayPin = 23; // Change this if you used a different pin
void setup() {
pinMode(relayPin, OUTPUT);
// Initialize Bluetooth with a custom name
SerialBT.begin("ESP32_Relay_Controller");
Serial.begin(115200);
Serial.println("Device Started. Waiting for pairing...");
}
void loop() {
// Check if data is coming from the phone
if (SerialBT.available()) {
char command = SerialBT.read();
if (command == '1') {
digitalWrite(relayPin, HIGH); // Turn Relay ON
Serial.println("Relay turned ON");
}
else if (command == '0') {
digitalWrite(relayPin, LOW); // Turn Relay OFF
Serial.println("Relay turned OFF");
}
}
delay(20); // Small stability delay
}
Code Breakdown:
#include "BluetoothSerial.h": This library comes pre-installed with the ESP32 board package in Arduino IDE. You do not need to download it manually.SerialBT.read(): This function captures one character at a time sent from your phone.digitalWrite(): This sends the voltage signal to the relay module to mechanically switch the circuit.
Step 3: How to Test (Before Building the App)
Pro Tip: Don't build the mobile app yet! Verify the hardware works first.
- Upload the code to your ESP32.
- Download a generic "Bluetooth Serial Terminal" app from the Play Store.
- Pair your phone with the device named "ESP32_Relay_Controller".
- Open the terminal app and connect.
- Type 1 and send. You should hear the relay click. Type 0 to turn it off.
If this works, your hardware is perfect. Now you are ready to build the custom interface.
Resources
Get the complete source code and schematic diagrams from the repository:
📂 Download Arduino Sketch (GitHub)
Watch the Full Tutorial
Watch the step-by-step upload process and the live relay test in the video below:
Code uploaded successfully? Time to design the interface. Move on to Part 3: App Interface Design.
Comments
Post a Comment