DEV Community

Hedy
Hedy

Posted on

How to use a microcontroller to control a relay?

Controlling a relay with a microcontroller (e.g., Arduino, ESP32, Raspberry Pi Pico) is a fundamental skill for switching high-voltage devices (like lights, motors, or appliances) safely. Here’s a step-by-step guide:

1. Key Components

2. Relay Wiring
Most relay modules have:

  • Control Pins: VCC, GND, IN (signal)
  • Load Pins: COM (common), NO (Normally Open), NC (Normally Closed)

Connections

Load Wiring
COM → High-voltage power (e.g., 120V AC)
NO → Load (e.g., bulb) → Return to neutral
https://i.imgur.com/JQ8WzVl.png
(Always keep high-voltage wiring insulated!)

3. Example Code (Arduino)

cpp
const int relayPin = 2;  // GPIO D2

void setup() {
  pinMode(relayPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // Turn relay ON (closes circuit)
  digitalWrite(relayPin, HIGH);
  Serial.println("Relay ON - Circuit CLOSED");
  delay(2000);

  // Turn relay OFF (opens circuit)
  digitalWrite(relayPin, LOW);
  Serial.println("Relay OFF - Circuit OPEN");
  delay(2000);
}
Enter fullscreen mode Exit fullscreen mode

4. Example Code (ESP32/ESP8266 - MicroPython)

python
from machine import Pin
import time

relay = Pin(2, Pin.OUT)  # GPIO2

while True:
    relay.value(1)  # ON
    print("Relay ON")
    time.sleep(2)

    relay.value(0)  # OFF
    print("Relay OFF")
    time.sleep(2)
Enter fullscreen mode Exit fullscreen mode

5. Important Considerations
A. Relay Module Types
Active LOW vs. Active HIGH:

  • Some relays trigger when IN is LOW (LOW = ON). Check your module’s datasheet.
  • Adjust code: digitalWrite(relayPin, LOW) to turn ON.

B. Power Isolation

  • Use an optocoupler-based relay module to protect your microcontroller from high-voltage noise.
  • Avoid sharing GND between high-voltage and microcontroller circuits.

C. Flyback Diode
If controlling inductive loads (motors, solenoids), add a diode across the relay coil to prevent voltage spikes.

6. Advanced Control
A. PWM Control (For Solid-State Relays)

cpp
analogWrite(relayPin, 128);  // 50% duty cycle (for SSR)
Enter fullscreen mode Exit fullscreen mode

B. WiFi/Bluetooth Control (ESP32)

python
# ESP32 with Web Server (MicroPython)
import network
import socket
from machine import Pin

relay = Pin(2, Pin.OUT)
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect("WiFi_Name", "Password")

def web_page():
    html = """<html><body>
    <a href="/on"><button>ON</button></a>
    <a href="/off"><button>OFF</button></a>
    </body></html>"""
    return html

s = socket.socket()
s.bind(('0.0.0.0', 80))
s.listen(5)

while True:
    conn, addr = s.accept()
    request = conn.recv(1024)
    if "/on" in request:
        relay.value(1)
    elif "/off" in request:
        relay.value(0)
    conn.send(web_page())
    conn.close()
Enter fullscreen mode Exit fullscreen mode

7. Troubleshooting

Safety Tips

  • Never touch high-voltage terminals when powered.
  • Use insulated wires for AC connections.
  • Double-check wiring before powering on.

Applications

  • Home automation (lights, fans).
  • Industrial control systems.
  • DIY projects (coffee maker timer, etc.).

Top comments (0)