There is a particular satisfaction that comes from saying "Alexa, turn off the lights" and watching it actually happen on hardware you built yourself. ESP32 home automation with Alexa is one of the most practical and rewarding IoT projects a maker can build. It teaches you wireless networking, cloud API integration, relay control, and embedded firmware all in one complete circuit.
This guide walks through the complete process of building a working smart switch using an ESP32 and integrating it with Amazon Alexa for voice control. No proprietary smart home hubs required. No subscription fees. Just open source firmware, a handful of components, and a finished product that works identically to commercial smart switches that cost many times more.
Before starting, if you are new to the ESP32 and want to understand why it is the right microcontroller for connected projects like this one, our comparison of ESP32 vs Arduino for IoT projects explains the hardware differences that make the ESP32 well-suited for Wi-Fi-enabled builds.
What You Will Build
By the end of this guide, you will have a smart switch that does the following:
A relay module connected to the ESP32 controls a mains-powered device such as a lamp, a fan, or any standard household appliance. The ESP32 connects to your home Wi-Fi network and runs a lightweight firmware called SinricPro, which registers it as a virtual Alexa smart home device. Alexa discovers the switch automatically through her smart home skill and adds it to your device list. From that point on, voice commands via any Alexa device and the Alexa app on your phone both control the relay in real time.
The build also includes a physical push-button wired to the ESP32 so that the switch can be toggled manually without a voice command or a phone. The physical and voice control states remain synchronised.
Components Required
|
Component |
Quantity |
|
ESP32 development board (38-pin or 30-pin) |
1 |
|
5V single-channel relay module |
1 |
|
Tactile pushbutton |
1 |
|
10k ohm resistor |
1 |
|
LED with 220 ohm resistor (optional status indicator) |
1 each |
|
Jumper wires |
As needed |
|
Breadboard or custom PCB |
1 |
|
USB cable for programming |
1 |
|
5V power supply for the ESP32 |
1 |
You can source the ESP32 board, relay module, resistors, and supporting electronic components from the Think Robotics microcontrollers and sensors collection, which carries the components needed for this and similar ESP32-based builds.
Understanding the Circuit Before Building It
The ESP32 operates at 3.3V logic. Most relay modules are designed for 5V control signals. Still, the vast majority of relay modules sold for maker projects use an optocoupler input stage that reliably responds to the 3.3V output from an ESP32 GPIO pin. Check the relay module datasheet to confirm, but in practice, this works without issue on standard relay breakout boards.
The relay itself is an electromechanical switch. When the signal from the ESP32 GPIO energises the control coil, an internal armature moves, connecting the COM (common) terminal to either the NO (normally open) or NC (normally closed) terminal. For a smart switch application, you wire your mains load between COM and NO. When the relay is off, the circuit is open, and the appliance receives no power. When the relay fires, the circuit closes, and the appliance turns on.
A critical safety note: This project involves controlling mains voltage (220V AC in India). The relay module provides electrical isolation between the low-voltage ESP32 circuit and the mains side. Never touch the mains wiring when the circuit is powered. If you are not experienced with mains wiring, work only on the low-voltage side and have a qualified electrician complete the mains connections. All testing during development should be done with the mains wiring disconnected.
Wiring the Circuit
Connect the components as follows. GPIO numbers refer to the standard 38-pin ESP32 devkit boards.
The relay module has three control pins: VCC, GND, and IN. Connect VCC to the 5V pin on the ESP32 devkit (the VIN pin, which passes through the onboard USB power regulator at 5V). Connect GND to any GND pin on the ESP32. Connect IN to GPIO 26.
The pushbutton connects between GPIO 25 and GND. Wire the 10 kΩ resistor between GPIO 25 and the 3.3V pin to act as a pull-up resistor. When the button is not pressed, GPIO 25 reads HIGH through the resistor. When the button is pressed, GPIO 25 is pulled directly to GND, and the pin reads LOW. This is a standard active low button configuration.
If you are adding the optional status LED, connect the LED in series with the 220 ohm resistor between GPIO 27 and GND. The LED illuminates when GPIO 27 is HIGH, giving a local visual indication of the relay state independent of the relay module's own LED.
Setting Up the SinricPro Account
SinricPro is a cloud platform that bridges your ESP32 firmware to Amazon Alexa and Google Home. It provides a free tier that covers this project entirely. Creating an account and registering a device takes under ten minutes.
Go to sinric.pro and create a free account. Once logged in, navigate to the Devices section and click Add Device. Select Switch as the device type. Give it a name that Alexa will recognise clearly, such as "Living Room Lamp" or "Desk Fan." Avoid generic names like "Switch" because Alexa handles named devices more reliably in multi-device homes.
After saving the device, SinricPro generates three credentials you need for the firmware: an App Key, an App Secret, and a Device ID. Copy all three and keep them in a place that's accessible. These go directly into your Arduino sketch.
Installing the Required Libraries
Open the Arduino IDE. Make sure you have the ESP32 board support package installed through the Boards Manager. If you have not done this, search for esp32 by Espressif Systems in the Boards Manager and install the latest stable version.
Next, install the required libraries through the Library Manager. Search for and install each of the following: SinricPro by Boris Jaeger, ArduinoJson (version 6.x), and WebSockets by Markus Sattler. SinricPro depends on both ArduinoJson and WebSockets to function, so all three are required.
Writing the Firmware
Create a new sketch in the Arduino IDE. The firmware structure has four main components: credential definitions, relay and button pin definitions, the Alexa callback function that runs when a voice command arrives, and the setup and loop functions that initialise the system and handle button input.
cpp
#include <Arduino.h>
#include <WiFi.h>
#include <SinricPro.h>
#include <SinricProSwitch.h>
// Wi-Fi credentials
#define WIFI_SSID "YourNetworkName."
#define WIFI_PASS "YourNetworkPassword."
// SinricPro credentials
#define APP_KEY "your-app-key-here"
#define APP_SECRET "your-app-secret-here"
#define SWITCH_ID "your-device-id-here"
// Pin definitions
#define RELAY_PIN 26
#define BUTTON_PIN 25
#define LED_PIN 27
bool currentRelayState = false;
// Callback: runs when Alexa sends an on or off command
bool onPowerState(const String &deviceId, bool &state) {
currentRelayState = state;
digitalWrite(RELAY_PIN, currentRelayState ? HIGH : LOW);
digitalWrite(LED_PIN, currentRelayState ? HIGH : LOW);
return true;
}
void setupWiFi() {
Serial.print("Connecting to Wi-Fi");
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" Connected.");
}
void setupSinricPro() {
SinricProSwitch &mySwitch = SinricPro[SWITCH_ID];
mySwitch.onPowerState(onPowerState);
SinricPro.begin(APP_KEY, APP_SECRET);
}
void handleButton() {
static bool lastButtonState = HIGH;
bool buttonState = digitalRead(BUTTON_PIN);
if (buttonState == LOW && lastButtonState == HIGH) {
delay(50); // debounce
currentRelayState = !currentRelayState;
digitalWrite(RELAY_PIN, currentRelayState ? HIGH : LOW);
digitalWrite(LED_PIN, currentRelayState ? HIGH : LOW);
SinricProSwitch &mySwitch = SinricPro[SWITCH_ID];
mySwitch.sendPowerStateEvent(currentRelayState);
}
lastButtonState = buttonState;
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW);
setupWiFi();
setupSinricPro();
}
void loop() {
handleButton();
SinricPro.handle();
}
Replace the placeholder strings in the credential definitions with your actual Wi-Fi SSID, Wi-Fi password, and the three SinricPro credentials from your account. Select your ESP32 board from the Tools menu, select the correct COM port, and upload the sketch.
Open the Serial Monitor at 115200 baud. You should see the board connect to Wi-Fi and then print a confirmation that it has connected to the SinricPro service. If the Wi-Fi connection fails, check your SSID and password. If the SinricPro connection fails, check your App Key and App Secret.
Linking to Alexa
Open the Alexa app on your phone. Navigate to More, then Skills and Games. Search for SinricPro and enable the skill. Sign in with your SinricPro account credentials when prompted. Alexa will link to your SinricPro account and discover the devices registered there.
Say "Alexa, discover devices" or tap Discover Devices in the app. Alexa will find the device you named in SinricPro and add it to your smart home device list.
Test with a voice command: "Alexa, turn on Living Room Lamp." The relay should click, the LED should illuminate, and the appliance connected to the relay's NO terminal should power on. "Alexa, turn off the living room lamp" reverses it.
Test the physical button. Pressing it should toggle the relay and immediately synchronise the new state with Alexa via the sendPowerStateEvent call in the firmware. If you check the device status in the Alexa app after pressing the physical button, it should reflect the new state correctly.
Troubleshooting Common Issues
The relay does not respond to voice commands, but Wi-Fi connects correctly. Check that the SinricPro credentials in your sketch exactly match those in your SinricPro account. A single incorrect character in the App Key, App Secret, or Device ID prevents authentication silently.
Alexa says the device is not responding. This typically means the ESP32 has lost its Wi-Fi connection or the SinricPro cloud service timed out the connection. Add a WiFi reconnection check inside the loop function that re-runs setupWiFi and setupSinricPro if WiFi.status() is not WL_CONNECTED.
The physical button state does not update in the Alexa app. Confirm that the sendPowerStateEvent call is within the handleButton function and is being invoked. Check the Serial Monitor for any error messages from the SinricPro library during the button-press event.
The relay clicks repeatedly without input. This is usually a button bounce. Increase the debounce delay from 50ms to 100ms and add a check that the button is HIGH before registering another press.
For a detailed reference on SinricPro library functions, callbacks, and multi-device configurations, the SinricPro official documentation covers the complete API with examples for switches, dimmers, thermostats, and sensors.
Extending the Project
This single-switch build is a complete and functional project on its own. It is also a foundation that extends naturally in several directions.
Adding more relays and registering additional Switch devices in SinricPro scales the build to control multiple appliances from the same ESP32. The dual-core architecture means the ESP32 handles multiple device callbacks without the timing conflicts that would affect a single-core microcontroller.
Adding a DHT22 temperature and humidity sensor and registering a Thermostat device in SinricPro alongside the switch lets the same board report environmental data to Alexa while still controlling the relay. Alexa can then expose the temperature data to routines and automations.
Replacing the breadboard build with a custom PCB, mounting it inside a standard electrical box, and connecting it directly behind a wall switch plate produces a finished installation that is indistinguishable from a commercial smart switch from the outside.
For a thorough technical reference on building IoT systems around the ESP32, including Wi-Fi connection management, power-saving modes, and secure credential storage, the Random Nerd Tutorials ESP32 project library is one of the most comprehensive free resources available for this class of project.
The Think Robotics ESP32 and IoT components section includes relay modules, ESP32 devkits, sensors, and enclosures, suitable for taking this project from breadboard to a finished installation.
Conclusion
Building an ESP32 home-automation Alexa smart switch from scratch is a project that delivers immediate, practical value while teaching skills that apply across the entire field of connected hardware. The SinricPro firmware stack abstracts the complexity of the Alexa API into a clean callback model, keeping the firmware readable and maintainable. The physical button integration ensures the device continues to work even when the network is down. The relay module provides safe, isolated control of mains-powered appliances.
The result is a smart switch that you understand completely, can repair and modify, and can replicate across every room in your home without paying for commercial hardware or proprietary ecosystems.
Build it once, understand it fully, and the next smart home project becomes significantly faster to execute.