Skip to content

ESP32 · Build guide

ESP32 Smart Home Automation with Relay & Telegram Bot Control

Control your home appliances from anywhere using ESP32, a 4-channel relay module, and Telegram Bot. No cloud subscription needed — just your phone.

ESP32 Smart Home Automation with Relay & Telegram Bot Control
Difficulty
Advanced
Read time
20 min
Board
ESP32
Author
SolderHub
Published
Oct 17, 2026
Views
2

The Idea

I got tired of getting up to turn off the fan at night. Sounds lazy, I know. But that's honestly how this project started — lying in bed, too warm, too comfortable to move.

So I built a Telegram-controlled relay switch using my ESP32. Now I control four appliances from my phone — fan, lights, water pump, and a desk lamp — without any monthly subscription or cloud service.

Here's the full build.


What You'll Need

Hardware:

  • ESP32 DevKit v1
  • 4-channel 5V relay module
  • Jumper wires (male to male)
  • USB power adapter (5V 2A minimum)
  • Any AC appliance to control (start with a lamp — safer)

Software:

  • Arduino IDE (2.x recommended)
  • Libraries: WiFi.h (built-in), UniversalTelegramBot, ArduinoJson

How It Works

The ESP32 connects to your WiFi. It then polls the Telegram Bot API every 1.5 seconds using an HTTPS GET request. When you send /fan on from your phone, the ESP32 reads the message, triggers GPIO pin 26, and the relay clicks ON.

Simple. Reliable. No middleman.


Circuit Connections

Relay Module PinESP32 Pin
IN1GPIO 26
IN2GPIO 27
IN3GPIO 14
IN4GPIO 12
VCC5V (VIN)
GNDGND

⚠️ Never connect AC mains directly without proper insulation. Use pre-wired relay boards with terminal blocks.


sketch.ino
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>

// WiFi credentials
const char* ssid     = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";

// Telegram Bot Token from @BotFather
const char* BOT_TOKEN = "YOUR_BOT_TOKEN";

// Your Telegram chat ID from @userinfobot
const String CHAT_ID = "YOUR_CHAT_ID";

// Relay pins (LOW = ON for most relay modules)
const int RELAY1 = 26; // Fan
const int RELAY2 = 27; // Light
const int RELAY3 = 14; // Water pump
const int RELAY4 = 12; // Desk lamp

WiFiClientSecure client;
UniversalTelegramBot bot(BOT_TOKEN, client);

unsigned long lastCheck = 0;
const int CHECK_INTERVAL = 1500; // ms

void handleMessage(String text, String chat_id) {
  text.toLowerCase();

  if (text == "/fan on")        { digitalWrite(RELAY1, LOW);  bot.sendMessage(chat_id, "✅ Fan turned ON",  ""); }
  else if (text == "/fan off")  { digitalWrite(RELAY1, HIGH); bot.sendMessage(chat_id, "❌ Fan turned OFF", ""); }
  else if (text == "/light on") { digitalWrite(RELAY2, LOW);  bot.sendMessage(chat_id, "✅ Light turned ON", ""); }
  else if (text == "/light off"){ digitalWrite(RELAY2, HIGH); bot.sendMessage(chat_id, "❌ Light turned OFF", ""); }
  else if (text == "/pump on")  { digitalWrite(RELAY3, LOW);  bot.sendMessage(chat_id, "✅ Pump ON", ""); }
  else if (text == "/pump off") { digitalWrite(RELAY3, HIGH); bot.sendMessage(chat_id, "❌ Pump OFF", ""); }
  else if (text == "/lamp on")  { digitalWrite(RELAY4, LOW);  bot.sendMessage(chat_id, "✅ Lamp ON", ""); }
  else if (text == "/lamp off") { digitalWrite(RELAY4, HIGH); bot.sendMessage(chat_id, "❌ Lamp OFF", ""); }
  else if (text == "/status") {
    String status = "📊 Current Status:\n";
    status += "Fan: "   + String(digitalRead(RELAY1) == LOW ? "ON" : "OFF") + "\n";
    status += "Light: " + String(digitalRead(RELAY2) == LOW ? "ON" : "OFF") + "\n";
    status += "Pump: "  + String(digitalRead(RELAY3) == LOW ? "ON" : "OFF") + "\n";
    status += "Lamp: "  + String(digitalRead(RELAY4) == LOW ? "ON" : "OFF");
    bot.sendMessage(chat_id, status, "");
  }
  else if (text == "/help") {
    String help = "🤖 SolderHub Home Bot Commands:\n\n";
    help += "/fan on | /fan off\n";
    help += "/light on | /light off\n";
    help += "/pump on | /pump off\n";
    help += "/lamp on | /lamp off\n";
    help += "/status — see all states\n";
    bot.sendMessage(chat_id, help, "");
  }
}

void setup() {
  Serial.begin(115200);

  pinMode(RELAY1, OUTPUT); digitalWrite(RELAY1, HIGH);
  pinMode(RELAY2, OUTPUT); digitalWrite(RELAY2, HIGH);
  pinMode(RELAY3, OUTPUT); digitalWrite(RELAY3, HIGH);
  pinMode(RELAY4, OUTPUT); digitalWrite(RELAY4, HIGH);

  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500); Serial.print(".");
  }
  Serial.println("\nConnected! IP: " + WiFi.localIP().toString());

  client.setInsecure(); // For Telegram SSL
  bot.sendMessage(CHAT_ID, "🏠 Home Bot is online! Send /help", "");
}

void loop() {
  if (millis() - lastCheck > CHECK_INTERVAL) {
    int newMessages = bot.getUpdates(bot.last_message_received + 1);
    while (newMessages) {
      for (int i = 0; i < newMessages; i++) {
        if (bot.messages[i].chat_id == CHAT_ID)
        handleMessage(bot.messages[i].text, bot.messages[i].chat_id);
      }
      newMessages = bot.getUpdates(bot.last_message_received + 1);
    }
    lastCheck = millis();
  }
}

Setting Up Your Telegram Bot

  1. Open Telegram → search @BotFather
  2. Send /newbot → give it a name → get your token
  3. Search @userinfobot → send /start → copy your Chat ID
  4. Replace the token and chat ID in the code above

Troubleshooting

Bot not responding?

  • Check your WiFi credentials
  • Make sure Chat ID matches exactly (can be negative for group chats)
  • Some ISPs block Telegram — try a different network

Relay clicking but appliance not working?

  • Check if your relay is active LOW or active HIGH
  • Most blue relay modules are active LOW (LOW = ON)

ESP32 keeps restarting?

  • Relay module drawing too much current from 3.3V pin
  • Power the relay VCC from 5V (VIN pin), not 3.3V

What's Next?

Once this works, you can add:

  • A small OLED display showing appliance status
  • Scheduled ON/OFF using NTP time
  • Voice control via Google Assistant + IFTTT

The foundation is solid. Build on it.


RFID Reader Wiring and Card Enrollment

The MFRC522 reader uses SPI and is a 3.3 V device. Connect its SDA/SS, SCK, MOSI, MISO, and RST pins to the SPI and reset pins defined in the sketch, then connect 3.3 V and GND. On an Arduino Uno, do not power the MFRC522 from 5 V and do not drive its signal pins with 5 V logic unless the specific breakout explicitly includes level shifting. Use a compatible logic-level shifter where required. The label SDA on this module usually means SPI chip select, not I²C data.

SignalUno R3 common SPI pinNotes
SCKD13SPI clock
MOSID11Controller to reader
MISOD12Reader to controller
SS/SDAD10, if used by sketchSPI chip select
RSTPin defined in sketchReset
VCC3.3 VDo not use 5 V
GNDGNDCommon reference

Use the actual sketch pin definitions if they differ from this common mapping. Read a card UID during setup and enroll only test cards you control. Store the UID list in a clear, documented format and provide a way to remove a card when access should be revoked.

Security Limitations

A basic MFRC522 UID check is a learning demonstration, not a secure access-control system. Card identifiers can be copied or emulated on some card types, and UID-only authorization does not provide strong cryptographic authentication. Do not use this design as the sole lock for a home, workplace, or anything that protects people or valuable property. A real access system needs secure credentials, protected key storage, audit controls, and a fail-safe mechanical design.

Keep the lock actuator on a suitable transistor or relay driver; never power a solenoid or lock directly from an Arduino GPIO. Use a separate supply rated for the actuator's current and protect inductive loads with an appropriate flyback path. Decide what the lock should do during power loss and controller reset, and test that behavior before attaching the mechanism to a door.

Test Procedure and Troubleshooting

  1. Test reader detection and card UID output before connecting the lock.
  2. Verify that an enrolled test card is accepted and an unknown card is rejected.
  3. Confirm that the lock output returns to its safe state after the activation interval.
  4. Test repeated scans, reset, and power cycling.
  5. If the reader is not detected, check 3.3 V supply, SPI pin mapping, reset wiring, and logic levels.
  6. If the reader works only intermittently, shorten SPI wires and check for supply noise.

The access log can help with a classroom demonstration, but avoid storing personal data unnecessarily. For any real deployment, obtain appropriate consent and review privacy and physical-security requirements.

Ultrasonic Sensor Wiring and Distance Calculation

For a common HC-SR04 module, connect VCC to its rated 5 V supply, GND to Arduino GND, and TRIG and ECHO to the digital pins defined in the sketch. The Uno can accept the sensor's 5 V ECHO signal directly; 3.3 V boards such as many ESP32 variants generally require a divider or level shifter on ECHO. Check the exact sensor version before wiring.

The sensor estimates distance by timing the ultrasonic echo. A common approximation in air at room temperature is distance in centimetres equals echo pulse duration in microseconds divided by about 58. This is an estimate: temperature, target angle, surface material, and sensor blind zones affect the reading. Take multiple samples and reject timeouts instead of treating a missing echo as a real distance.

Set Practical Warning Thresholds

Choose warning and stop distances based on the vehicle's speed and the sensor's real mounting position. A small toy vehicle needs a larger stopping margin than the sensor's measurement error alone suggests. Add hysteresis between warning-on and warning-off thresholds so the buzzer or indicator does not chatter when the distance fluctuates near the boundary. A parking sensor is an aid, not a substitute for direct observation.

Installation and Troubleshooting

  1. Test the sensor stationary with a flat target at several known distances.
  2. Keep the sensor face clear of the chassis and ensure it points straight toward the target.
  3. Check that TRIG and ECHO match the code and that the ground connection is secure.
  4. If readings jump, inspect loose wires, angled targets, soft materials, and electrical noise from motors.
  5. If no echo is received, use a timeout and display an explicit out-of-range state rather than an arbitrary zero distance.
  6. Test the buzzer or LED independently before integrating the full alert logic.

Mount the module rigidly and protect its electronics from rain unless the particular sensor is rated for outdoor use. If this project is fitted to a moving vehicle, test at walking speed in an open area first and do not depend on a single ultrasonic sensor for collision avoidance.

Sensor Differences and Wiring

The DHT22 measures temperature and relative humidity; the BMP280 measures temperature and atmospheric pressure but not humidity. Combining them provides humidity from the DHT22 and pressure plus a second temperature reading from the BMP280. Treat the two temperature readings as separate measurements because sensor placement, response time, and self-heating can make them differ.

For the BMP280 I²C interface on an Arduino Uno, connect SDA to A4 and SCL to A5. Connect the DHT22 data output to the digital pin configured in the sketch, and follow the sensor breakout's supply requirements. Bare sensor modules may not tolerate the same voltage as breakout boards with regulators or level shifters. If using a bare DHT22, it typically requires a pull-up resistor on the data line; many modules already include one.

Measurement Quality

Place the sensors away from the Uno regulator, direct sunlight, warm displays, and drafts from fans if the goal is to measure room conditions. Give the sensors time to settle after power-up. Do not compare a newly powered sensor's first reading directly with a stabilized reference instrument. For pressure, record units and remember that weather changes and elevation both affect the reading.

Validation and Troubleshooting

  1. Confirm the BMP280 is detected at its I²C address, commonly 0x76 or 0x77.
  2. Confirm the DHT library is configured for the correct sensor model and data pin.
  3. Check that the BMP280 is not actually a BMP180 or another visually similar module.
  4. If readings are NaN or absent, inspect pull-ups, supply voltage, wiring, and library initialization.
  5. Compare temperature and humidity with a reference device after allowing both to stabilize.
  6. Use a reasonable sampling interval; the DHT22 should not be polled too rapidly.

This station is suitable for learning sensor integration and displaying environmental trends. It should not be described as a calibrated weather instrument unless it has been compared with traceable references and installed in an appropriate radiation-shielded enclosure.

LED Wiring and Current Limiting

Connect each LED through its own current-limiting resistor. Do not connect an LED directly between a GPIO and ground. The resistor value depends on the LED forward voltage and desired current; for a simple indicator, a few milliamps is usually enough. Confirm the pin numbers in the sketch and ensure they are all configured as outputs. The Mega 2560 has more digital pins than the Uno, but each pin still has current limits and the board has an overall current budget.

Circuit partConnection guidance
LED anodeDigital output through a resistor
LED cathodeGND, if using active-high wiring
ResistorOne per LED, typically selected for a few mA
Common groundConnect all LED return paths to board GND

For a longer LED strip or many LEDs, use a transistor or driver IC rather than drawing the combined load directly from GPIO pins. Check the board's official electrical limits before selecting current.

Timing and Pattern Changes

A basic LED chaser turns one output on at a time, waits, then advances to the next output. The delay controls the animation speed. If you add buttons, serial control, or sensors later, replace long blocking delays with a millis()-based timing loop so the microcontroller can respond while the pattern runs. Make sure the final LED returns to the first LED without indexing outside the configured pin array.

Test and Troubleshooting

  1. Test a single LED and resistor before wiring the full sequence.
  2. Verify LED polarity; the longer lead is commonly the anode, but check the part if leads have been trimmed.
  3. Confirm every LED has its own resistor and that no adjacent pins are accidentally shorted.
  4. If an LED stays on, inspect its pin mapping and whether the code sets the pin LOW between steps.
  5. If the pattern skips or behaves unpredictably, check the pin array length against the loop bounds.
  6. Test at a slow interval first, then increase speed after verifying the sequence.

This project teaches digital outputs, arrays, and timing. It can be extended with selectable patterns or speed control, but keep the current-limiting resistors and safe GPIO loading in place.

Relay Wiring and Boot-State Safety

The relay module must be compatible with the ESP32's 3.3 V GPIO logic and the load current. Some relay boards are active-low, and some do not reliably trigger from 3.3 V logic; confirm the module's input specification rather than assuming that any 5 V relay board will work. Power the relay coil from a suitable supply and connect the logic ground as required by the module. Never power a relay coil or household load directly from an ESP32 GPIO.

Set the output to its safe state as early as possible during startup, before connecting to Wi-Fi or a messaging service. Choose the default relay state deliberately and verify it during reset, brownout, firmware upload, and network loss. For lights and other mains-powered loads, use a properly rated enclosed module, appropriate fusing and strain relief, and qualified mains installation. Do not build or test mains wiring on a breadboard.

Network Control and Authentication

If the relay is controlled by a Telegram bot or another remote service, validate every incoming command and restrict control to authorized users or chat IDs. Do not publish bot tokens, Wi-Fi passwords, or private credentials in a public sketch. Store secrets outside shared source code and rotate any token that has been accidentally exposed. Report command success only after the controller has confirmed the output state.

A remote service can be unavailable, delayed, or duplicated. Keep the local output state and remote reported state synchronized, and decide what should happen when Wi-Fi drops. For safety-sensitive loads, remote connectivity should not bypass local interlocks or protection.

Test Plan

  1. Test relay input polarity with the load disconnected.
  2. Confirm startup and reset do not cause an unintended relay pulse.
  3. Verify the allowed user list rejects an unauthorized test account.
  4. Disconnect Wi-Fi and confirm the local relay behavior remains predictable.
  5. Reboot the ESP32 while the relay is commanded on and verify the chosen boot policy.
  6. Test with a low-voltage lamp or other safe load before any mains installation.

If the ESP32 resets when the relay changes state, check the relay supply, grounding, decoupling, and inductive interference. If the relay never changes state, inspect active-low logic, input compatibility, and the GPIO number. A reliable smart switch needs safe electrical design as well as working network code.

Build Sheet

Take this build with you

We'll email you the parts list for ESP32 Smart Home Automation with Relay & Telegram Bot Control, with parts information, available SolderHub Simulator links, and source-code links, so you can order and build later. You'll also get new builds as they're published.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.

Topicsesp32home-automationtelegramrelayiotwifi

Questions & Answers