Try Embedded

Switch a lamp with a relay

Use a relay to switch a separate circuit (an LED "lamp") on and off from a microcontroller pin.

Basic · Beginner

In a real product: Smart plug (Smart home): A relay switches the mains load.

A relay is a switch worked by an electromagnet. A small current through its coil pulls the contacts together, so a microcontroller can switch a completely separate circuit: a lamp, a pump, a mains appliance. Here the "lamp" is an LED, switched once a second.

What you'll learn

  • The parts of a relay: the coil, the common (COM), normally open (NO) and normally closed (NC) contacts
  • Keeping the controlling circuit and the switched circuit apart
  • Why a relay is driven through a module (a transistor and a diode), not straight from a pin

How it works

A relay coil needs about 70 mA, more than the 20 mA a pin can give, and switching it off makes a voltage spike that can damage the pin. So the relay sits on a relay module: the module's VCC and GND power the coil, and its IN pin only switches an optocoupler and a transistor, with a flyback diode across the coil. Wiring a bare relay coil to a pin works in a simulator but not on the bench (the simulator shows a wiring warning if you try).

The module is set to high-level trigger, so pin 7 HIGH energises the coil and the contacts move: COM1 connects to NO1 instead of NC1. (Many modules ship as low-level trigger: then LOW turns the relay on.)

COM1 is wired to 5V, and NO1 to the resistor and LED. So the LED is off while the relay rests, and lights while pin 7 holds the relay on. You can hear the click on a real one.

Try this

  • Move the LED to NC1: now it is on while the relay is off.
  • Switch the relay with a pushbutton or a light sensor instead of a timer.
  • Set the module's trigger to low and change the sketch to match.
  • Give the module two channels and switch two lamps.

sketch.ino

// A relay on pin 7 switches an LED "lamp" on and off every second.
const int RELAY = 7;

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

void loop() {
  digitalWrite(RELAY, HIGH);   // energise the coil: COM1 connects to NO1
  Serial.println("Relay on: lamp on");
  delay(1000);
  digitalWrite(RELAY, LOW);    // release: COM1 goes back to NC1
  Serial.println("Relay off: lamp off");
  delay(1000);
}

Lessons behind it