Skip to content
GEEKnodes

Electronics

How to Use a Relay with Arduino or ESP32: Wiring, Modules, Safety

What a relay is, NO, NC and COM contacts, wiring it to Arduino or ESP32 with a transistor and flyback diode, active-low modules and mains voltage safety.

A relay lets an Arduino or an ESP32 switch on a lamp, a pump or a heater that runs on a different voltage, even mains voltage. The problem is that you can’t connect it directly to a pin, and cheap modules have quirks that confuse almost everyone. Here you’ll see how it works inside, how to wire it correctly and what precautions to take. If you haven’t decided which board to use yet, check out ESP32 vs Arduino first.

In short

  • The coil of a 5 V relay draws around 70 mA: you need a transistor and a flyback diode.
  • Almost all optocoupler modules are active low: LOW turns the relay on.
  • With a 3.3 V ESP32, a module designed for 5 V may not turn off; use your own transistor or a 3.3 V-compatible module.

What a relay is and how it works

An electromechanical relay is a switch moved by an electromagnet. It has two parts that are isolated from each other:

  • The coil: when current flows through it, it creates a magnetic field that pulls in a metal piece (the armature).
  • The contacts: the armature moves a blade that closes or opens the load circuit.

Since the coil and the contacts aren’t electrically connected, a 5 V signal can control a 12 V, 24 V or mains circuit. That isolation is the whole point of a relay.

COM, NO and NC contacts

The relays on Arduino modules are usually SPDT (one circuit, two positions) and have three output terminals:

TerminalNameState with the coil unpoweredState with the coil energized
COMCommon——
NONormally openDisconnected from COMConnected to COM
NCNormally closedConnected to COMDisconnected from COM

The rule of thumb: if you want the load to be off when the microcontroller is off or rebooting, use COM and NO. NC only makes sense when the load should run by default and the relay is there to cut it off.

Why you can’t connect it directly to a pin

A typical 5 V relay for modules has a coil of about 70 Ω, so it draws around 70 mA (5 V / 70 Ω). Check the value in your model’s datasheet, but it rarely goes below 50 mA.

On the Arduino Uno, each pin has an absolute maximum of 40 mA and the recommendation is not to exceed 20 mA. The ESP32 isn’t designed to drive loads that size either, and it also runs at 3.3 V, not enough for a 5 V coil.

There’s a second problem: the coil is an inductor. When you cut off its current, it generates a reverse voltage spike that can easily exceed tens of volts and destroy the pin or the transistor driving it.

Wiring with a transistor and flyback diode

If you use a bare relay (no module), the minimum circuit is a low-side NPN transistor and a diode in parallel with the coil:

   +5 V ───────┬──────────────┐
               │              │
             [COIL]      diode 1N4007
               │          (cathode to +5 V)
               ├──────────────┘
               │
            collector
  pin ─[R]─ base      (NPN: 2N2222, BC337…)
            emitter
               │
  GND ─────────┴──── GND shared with Arduino/ESP32
Schematic: relay coil between +5 V and the collector of an NPN, diode in parallel with the cathode to +5 V and a resistor from the pin to the base
The NPN supplies the coil current and the reverse-biased diode absorbs the spike at turn-off

Calculating the base resistor

To make the transistor work in saturation, use a forced gain of 10: the base current will be one tenth of the coil current.

  1. Coil current: 70 mA, so a base current of 7 mA.
  2. With a 5 V Arduino: R = (5 − 0.7) / 0.007 ≈ 614 Ω. Use 560 Ω.
  3. With a 3.3 V ESP32: R = (3.3 − 0.7) / 0.007 ≈ 371 Ω. Use 330 Ω.

The coil is still powered at 5 V; the ESP32 only drives the base. That’s why this circuit works just as well with 3.3 V. The BC547 handles 100 mA of collector current, cutting it close for 70 mA; a 2N2222 or a BC337 gives more margin. If you want to go over the calculation in more detail, it’s in the guide to the transistor as a switch.

The flyback (freewheeling) diode

The diode goes in parallel with the coil and reverse-biased: cathode (the band) toward +5 V, anode toward the collector. In normal operation it doesn’t conduct. At turn-off, the coil current flows through it and the spike disappears. A 1N4007 or a 1N4148 works for small relays.

Relay modules with an optocoupler

1, 2, 4 or 8-channel modules already include a transistor, a diode and an indicator LED. Many add an optocoupler (an LED and a phototransistor in the same package) between the IN pin and the transistor.

Active-low logic

On most of these modules, the optocoupler LED runs from VCC to the IN pin. Current flows when IN is at 0 V, so:

  • digitalWrite(pin, LOW) → relay on.
  • digitalWrite(pin, HIGH) → relay off.

To avoid a click at startup, write the idle level before setting the pin as an output:

const int PIN_RELE = 7;

void setup() {
  digitalWrite(PIN_RELE, HIGH);  // idle: relay off
  pinMode(PIN_RELE, OUTPUT);
}

void loop() {
  digitalWrite(PIN_RELE, LOW);   // turn the relay on
  delay(2000);
  digitalWrite(PIN_RELE, HIGH);  // turn it off
  delay(2000);
}

The JD-VCC jumper

Many modules have three pins next to the connector: GND, VCC and JD-VCC, with a jumper linking VCC and JD-VCC.

  • With the jumper on: the optocoupler and the coils share the same supply. It’s convenient, but there’s no real isolation.
  • With the jumper off: VCC (from the Arduino) powers only the optocoupler LED, and JD-VCC with its GND get a separate 5 V supply for the coils. To keep the isolation, don’t tie that GND to the Arduino’s.

Removing the jumper is a good idea with several relays: four coils add up to nearly 300 mA that no longer come from the board’s regulator.

5 V relays with a 3.3 V ESP32

This is the most asked-about problem. With the module powered at 5 V and the ESP32 outputting 3.3 V on HIGH, about 1.7 V remains between VCC and IN. Depending on the module, that’s enough to keep the optocoupler LED lit, and the relay doesn’t turn off or ends up in an uncertain state. On top of that, the ESP32 pin isn’t 5 V tolerant.

Reliable solutions:

  1. Your own transistor as in the schematic above: it works with 3.3 V with no tricks.
  2. Module with a JD-VCC jumper: VCC to 3.3 V and JD-VCC to 5 V. It works with many modules, but it depends on the resistors they use; test it before trusting it.
  3. A 3.3 V-compatible module or a relay with a 3 V coil.

Choose the pin carefully: avoid the ESP32 strapping pins (GPIO0, GPIO2, GPIO5, GPIO12, GPIO15) and the UART pins (GPIO1, GPIO3), because they change state at boot. GPIO25, GPIO26, GPIO27, GPIO32 or GPIO33 are safe choices on the classic ESP32.

Mains voltage safety

Mains voltage (120 V in the US, 230 V in Europe) can kill. If you have no training in electrical wiring, stick to low voltage (12 or 24 V) or use a certified smart plug.

  • Never build the mains side on a breadboard or with Dupont wires.
  • Put everything in a closed, insulating enclosure, with screw terminal blocks and cable glands.
  • Switch the hot (live) wire, not the neutral, and add a fuse rated for the load.
  • The “10 A 250 VAC” printed on the relay is for resistive loads. The traces on many cheap modules can’t handle that current; leave plenty of margin.
  • Motors, compressors and switching power supplies have inrush currents far above their rated draw.
  • Disconnect mains power before touching anything, even if the relay is “open”.

Solid-state relays (SSR)

An SSR switches with semiconductors instead of contacts: an optocoupler plus a triac (for AC) or a MOSFET (for DC).

FeatureElectromechanical relaySolid-state relay
NoiseAudible clickSilent
WearContacts with limited lifeNo moving parts
Control currentTens of mA (coil)A few mA (internal LED)
Off-state leakage currentNoneA few mA
Voltage dropAlmost noneAbout 1–1.6 V, gets hot
Load typeAC and DCOnly the one specified (AC or DC)
Fast switching and slow PWMPoorGood

Details worth knowing:

  • A zero-crossing AC SSR doesn’t work for DC: once on, it won’t turn off.
  • The leakage current can make an LED bulb glow faintly with the SSR off.
  • Above a few amps it needs a heatsink.
  • Many SSRs accept 3–32 V at the input, which makes them easy to use with an ESP32. Check the datasheet; there are clones with inflated ratings.

Common mistakes

MistakeSymptomFix
Relay connected directly to the pinArduino reboots or the pin gets damagedTransistor or module
No flyback diodeReboots, burned-out transistorDiode in parallel with the coil
Inverted logicThe relay is on when it should be offThe module is active low: HIGH turns it off
5 V module with ESP32The relay doesn’t turn offYour own transistor or JD-VCC at 5 V
Coils powered from USBReboots when several relays turn onSeparate 5 V supply
Load on NC by mistakeThe load runs with the relay offUse COM and NO
ESP32 strapping pinThe relay turns on at power-upUse another GPIO

Accessibility preferences

Quick profiles

Text and reading

Text size
Default
Line height
Default
Letter spacing
Default
Word spacing
Default

Colour

Motion and orientation

Cursor