Control a Relay from Your Phone with ESP32
The ESP32 has WiFi built in, so it can host a tiny web page. Open that page on your phone (on the same WiFi) and tap a button to switch a relay — your first step into home automation and IoT.
What You Need:
- 1x ESP32 Development Board
- 1x 5V Relay Module
- 1x Micro USB cable and a power bank or 5V adapter
- Jumper Wires
1. Wiring
- Relay VCC → ESP32 VIN (5V from USB)
- Relay GND → ESP32 GND
- Relay IN → ESP32 GPIO 26
2. The Code
In the Arduino IDE, install the ESP32 board package, select your board, and put your WiFi name and password in the code.
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "YOUR_WIFI";
const char* pass = "YOUR_PASSWORD";
const int relayPin = 26;
WebServer server(80);
bool on = false;
void page() {
String s = "<h1>ESP32 Relay</h1><p>Status: ";
s += on ? "ON" : "OFF";
s += "</p><a href='/toggle'><button style='font-size:24px'>Toggle</button></a>";
server.send(200, "text/html", s);
}
void setup() {
Serial.begin(115200);
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, HIGH); // off (active-low)
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) delay(500);
Serial.println(WiFi.localIP());
server.on("/", page);
server.on("/toggle", [] () {
on = !on;
digitalWrite(relayPin, on ? LOW : HIGH);
page();
});
server.begin();
}
void loop() { server.handleClient(); }3. Using It
Open the Serial Monitor (115200 baud) to see the IP address, e.g. 192.168.0.105. Type it into your phone's browser and tap Toggle.
New to ESP32? Read our Arduino vs ESP32 comparison first.
Need help? Stuck on wiring or code? Message us on WhatsApp at +880 1577-098376 and we will help you with your project.
