ESP32 - Relay

by DIYables in Circuits > Microcontrollers

5 Views, 0 Favorites, 0 Comments

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

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.

/*
* This ESP32 code is created by esp32io.com
*
* This ESP32 code is released in the public domain
*
* For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-relay
*/

#define RELAY_PIN 16 // ESP32 pin GPIO16 connected to the IN pin of relay

// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin as an output.
pinMode(RELAY_PIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
digitalWrite(RELAY_PIN, HIGH);
delay(1000);
digitalWrite(RELAY_PIN, LOW);
delay(1000);
}

Full Tutorial

The complete tutorial, wiring diagram and code explanation: https://esp32io.com/tutorials/esp32-relay