ESP32 - Relay
This is a compact build guide. The full tutorial, with the wiring diagram and a line-by-line walkthrough of the code, is here: https://esp32io.com/tutorials/esp32-relay
A relay lets an ESP32 switch a high-voltage device, such as an LED strip, lamp, pump, or lock, without exposing the ESP32 to that voltage. The ESP32 drives the relay's low-voltage input side, and the relay's output side handles the high-voltage load. This guide covers wiring the relay to an ESP32 and the code to turn it on and off.
Supplies
Everything below is what the build uses. The links go to the parts we make and test.
- 38-pin ESP32 ESP-WROOM-32 Dev Module - Narrow
- 38-pin ESP32 ESP-WROOM-32 Dev Module - Wide
- 30-pin ESP32 ESP-WROOM-32 Dev Module - Wide
- ESP32 Uno-form board
- ESP32 S3 Uno-form board
- USB Cable Type-A to Type-C (for USB-A PC)
- USB Cable Type-C to Type-C (for USB-C PC)
- Relay
- LED Strip
- Breadboard
- Jumper Wires
- DC Power Jack
- Screw Terminal Expansion Board for ESP32
- Breakout Expansion Board for ESP32
- Power Splitter for ESP32
- DIYables ESP32 Starter Kit (ESP32 included)
- DIYables ESP32 S3 Starter Kit (ESP32 S3 included)
- DIYables Sensor Kit (18 sensors/displays)
Wiring
The relay has a low-voltage input side and a high-voltage output side. On the input side, connect DC- to GND, DC+ to VCC (5V), and IN to an ESP32 digital pin such as GPIO16. On the output side, the screw terminal has NO (Normally Open), NC (Normally Closed), and COM pins; wire the high-voltage device, such as an LED strip powered by a 12V adapter, through these terminals. The ESP32 can be powered via USB cable or through its Vin pin.
How It Works
The relay is a programmable switch: the ESP32 controls it by setting the IN pin LOW or HIGH, which opens or closes the connection between the output terminals. You can configure the input as LOW-level or HIGH-level trigger, and the output as normally open or normally closed. 'Normally' refers to the state when IN is held LOW (0V). This lets a low-voltage ESP32 pin safely switch a high-voltage device connected through NO/NC/COM.
Code
The sketch sets the relay's control pin, GPIO16, as a digital output using pinMode(). It then uses digitalWrite() to drive that pin LOW (0V) or HIGH (3.3V), which switches the relay and in turn the connected device, with delay() used to create blinking. Uploading this code should make the LED strip connected through the relay blink on and off.
esp32-relay.ino - the sketch from the tutorial, unchanged.
Full Tutorial
The complete tutorial, wiring diagram and code explanation: https://esp32io.com/tutorials/esp32-relay