ESP32 MicroPython Relay

by DIYables in Circuits > Microcontrollers

10 Views, 0 Favorites, 0 Comments

ESP32 MicroPython Relay

esp32-micropython-relay-cover.jpg

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://newbiely.com/tutorials/esp32-micropython/esp32-micropython-relay

This build uses an ESP32 running MicroPython to switch a relay on and off, letting the low-voltage ESP32 control a high-voltage device such as an LED strip powered from a 12V adapter. The relay acts as the go-between, isolating the ESP32's GPIO signal from the higher voltage and current on the output side.

Supplies

Wiring

esp32-micropython-relay-wiring-diagram.jpg

The relay has an input side and an output side. On the input side, wire DC- to GND, DC+ to VCC (5V), and IN to a GPIO pin on the ESP32. On the output side, which is typically a screw terminal, wire COM and NO (normally open) to the high-voltage device, such as the LED strip powered by the 12V adapter. You can build this on a breadboard with jumper wires, or use a screw terminal expansion board for the ESP32 for a cleaner connection. Power the ESP32 either through its USB cable or through the Vin pin.

How It Works

The relay is a switch triggered by the signal on its IN pin. Depending on the module, it may use LOW level trigger or HIGH level trigger mode, meaning the relay activates when IN is pulled to 0V or to 5V respectively. The output side also has a default state: normally open or normally closed, where 'normally' refers to the state when IN is held LOW.

The ESP32 only needs to set its GPIO pin, the one wired to IN, to LOW or HIGH to switch the relay, and in turn the connected high-voltage device, on or off.

Code

The MicroPython code configures the GPIO pin connected to the relay's IN pin as a digital output. From there, the program writes HIGH or LOW to that pin to turn the relay on or off, which switches the connected high-voltage device, like the LED strip, accordingly.

esp32-micropython-relay.py - the sketch from the tutorial, unchanged.

"""
This ESP32 MicroPython code was developed by newbiely.com
This ESP32 MicroPython code is made available for public use without any restriction
For comprehensive instructions and wiring diagrams, please visit:
https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-relay
"""

from machine import Pin
import time

RELAY_PIN = 16 # The ESP32 pin GPIO16 connected to the relay pin

# Create a relay object using the Pin class
relay = Pin(RELAY_PIN, Pin.OUT)

# Main loop to toggle the relay
while True:
relay.value(1) # Set relay to HIGH (relay ON)
time.sleep(2) # Delay for 2 seconds
relay.value(0) # Set relay to LOW (relay OFF)
time.sleep(2) # Delay for 2 seconds

Full Tutorial

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