Saturday, September 27, 2025

Using Relays with the ESP32

 


This article covers the connection, code and use of relays with the ESP32.  While some slight changes may be needed, the information provided here will generally work with other MCUs and SBCs, such as the ESP8266, most Arduino boards and even the Raspberry Pi.

This article is a companion piece for the related YouTube video.  You may wish to also watch the video as it may contain additional information not covered here.

Why Use a Relay Instead of a Smart Plug/Switch?


Many commercial products, such as smart plugs, switches and dimmers contain a relay that can be externally controlled.


Some of these may also include an ESP inside.  So why build your own?  First, with a commercial device, you can only use the features provided.  What if you want to add a motion or presence sensor?  Or do something unique like switch between two circuits?  None of that is likely with a commercial device as you don't have access to the GPIO pins (unless you disassemble... and maybe not even then) nor to make changes to the default factory firmware.

By building your own relay device and using your own firmware (e.g. Arduino, ESPHome, Python, etc.) you will have complete local control.  No need to install a sketchy app on your phone or to provide any personal details to a third party.  No one can suddenly start demanding a subscription or brick your device if they close up shop and shut down their cloud servers. And your device will continue to work if there is an Internet outage.

Most importantly, when adding a relay to your own DIY projects, you can customize it to your exact needs... and it will never 'break' due to some sort of forced update from a manufacturer.  The device is truly yours.  As you'll see in the rest of this article, building your own gives you options and control that simply aren't possible with a commercial device.

Parts List


These are the parts used or shown either here in this article or as part of the related YouTube video.

Some of these links may be Amazon affiliate links.  Use of these links will not affect your pricing, but as an affiliate this channel may earn a small commission if you make a purchase.

Relay Basics


A relay is really nothing more than an electrically controlled switch.  It toggles the switch off/on based on a control signal... which can be sent by something like an ESP32.


One advantage of most relays is that you can use a low voltage control device (like the 5V or 3.3V DC from an ESP32) to switch a device with a different voltage... even something like an 120/240V AC circuit.  But there are a lot of things to consider before selecting a relay for your ESP project.

"Wet" vs. "Dry" contacts

This has nothing to do with water or moisture. Instead, it refers to how the relay and its switch are powered.  When a relay has "wet" contacts, it means both the control circuit and the switch are powered by a single power source.


This requires that components for both circuits (the control circuit and the switch or load circuit) must be compatible with the same voltage as they are likely internally connected.  This means if you were to attempt to switch a 120V  AC circuit, 120V AC could be passed back down the control line to the ESP32.  And you can imagine, the ESP32 won't be very happy for very long when you feed 120V AC into one of its GPIO pins!  


The product description may state wet contacts, but if it doesn't explicitly mention dry contacts or isolation between circuits, assume the relay has wet contacts.

A relay with "dry" contacts means the two circuits are isolated and therefore a low voltage control circuit and power a much larger (or smaller) voltage load circuit.  But this also means two separate power sources are needed.


When using an ESP32 to control a separate circuit, you will almost always use a dry contact relay unless the switched circuit also controls a 3.3V or 5V circuit.


These types of relays generally indicate dry contacts in the description, but they may specify the type or method of circuit isolation instead:


Optocoupler isolation is a common method of separating the circuits.  


Instead of using something like a coil, an LED is used on the control side and a photoresistor or other light detector is used on the switch side.  There is no physical electrical connection between the two circuits.  The only link is the light beam.  This is actually a very common type of relay, one you are most likely to use with your DIY projects and the type that I'll be using for the remainder of this article.

Voltage and Current Ratings


For dry contact or isolated relays, there are two different voltage and current ratings... one for the relay power and signal and one for the output or switched circuit.

Click to enlarge

Switch or Load Circuit Ratings

Both of these particular relays have the same ratings for the switched or load circuit: 
  • Up to 250V AC / 30V DC
  • 10A max
This means that both relays can handle either a DC circuit up to 30V or an AC circuit of up to 250V.  Therefore, it can be used to switch power to most household AC devices.  But do note the maximum 10A rating.  As a result, these relays may not be appropriate for large current draw devices, like space heaters, pumps or motors that might require higher amperage.

Relay and Signal Circuit Ratings

The second rating determines the voltage to both power the relay itself and the expected logic voltage for the control signal.  In the image above, the top relay is a 3V DC relay and the bottom one is a 5V DC relay.  So 3V or 5V are needed to power the relay device and the control or data signal needs to also be 3V or 5V to match the relay's power.

What isn't listed here is the current draw when the relay is energized.  This is important to know if we plan on powering the relay from the 3.3V or 5V power pin on the ESP32.  The power pins can only handle small amounts of current, so if the current draw is too high for the ESP32 pins, we'll need to power the relay separate from the ESP32.  But we'll test this shortly and measure the actual current draw.

Pinouts and Terminals


Let's take a look at the pinouts and any other jumpers on the relays.  The following is based on the relays from the parts list.  Other relays may have a different order or positioning of some terminals and/or different jumper settings.  Check your own relay's documentation carefully.

Relay/Control Terminals


On one end of the relay, you will find connections for the relay's power and the data or control signal.  This consists of either +3V DC (VCC) or +5V DC (DC+) depending on the relay, and then a ground (GND) connection and the control or data signal (IN).  Note that the relay expects a logical data voltage equal to the relay's voltage.  

Logical Voltage Levels

In other words, the 3V relay expects a logical 3V data signal while the 5V relay expects a 5V logical signal.


Load/Output Terminals


On the opposite end of the relay, you'll find the connections for the load or circuit to be switched.  Like a normal switch, you generally split the positive (+) side of the power circuit across the switch.  For these relays, you have a choice whether you want the switch to be 'normally closed' (circuit on when relay is off) or 'normally open' (circuit off when relay is off).  If you find that your relay is operating in the opposite manner than desired, simply flip your load connections from normally open to normally closed (or vice versa).

Note that having both an NC and NO connection provides some unique opportunities.  One option is to switch between two different circuits, as long as they are both using the same voltage.  One circuit would be active when the relay is "off" and the other would be active when the relay is "on".  I'll show an example of this a bit later in the article.

Jumpers

Your relay may have jumpers or pins that provide additional options.  Not all relays will be the same and even in my case the two relays have different jumper/options.


My 3V relay has two jumpers.  They connect the screw terminals to the relay's power.  In most cases, you'll leave both jumpers in place and provide the relay's power (3V in this case) via the screw terminals.  But if you have a special need, you can remove the jumpers and supply power directly to the pin closest to the relay itself.


The 5V relay only has a single jumper.  This determines whether the relay is triggered by a high or low logical data signal.  When set to the 'Low' side, then the relay will be energized when the module receives a 'Low' (0V) data signal.  When set to the 'High' side, then the relay will be energized when a 'High' (5V) logical signal is received.

For example, take this simple Arduino statement that outputs a high signal on the specified GPIO pin:

digitalWrite(RELAY_PIN, HIGH);

When executed, the relay would be turned on if the jumper is set to trigger on a high signal.  However, if the relay is set to trigger on a low signal, the same command would turn the relay off.  Used in combination with the NO/NC terminals, this provides a lot of flexibility for how you want the switched circuit to behave based on the GPIO data signal.  Again, if the relay is operating opposite of desired, you can either change the code, flip the high/low trigger jumper or switch the NO/NC connection.

Determining Current Draw of the Relay


Before getting into the wiring diagrams, we need to know the current draw on the control side.  This will determine whether we can use the ESP32's 5V or 3.3V pin to power the relay or whether we need to power the relays directly from the primary power supply.

Of course one way to do this is to look at a specification sheet for your particular relay.  In my case, both relays are using a module by Songle:


A simple Google search located the data sheet for these modules:


From this, I can see that the 3V relay will draw a nominal 120mA, while the 5V relay pulls a nominal 71mA.  This is a good starting point, but as I've shown in other component videos and articles, all clones or variations may not be created equal.  That's why, if possible, I recommend that you directly measure the current draw for the relay you plan on using.


Ignore the spaghetti wiring for the moment, but I set up a simple test rig and a couple of multimeters to measure the actual current draw.  For this test just know that I'm using a single ESP32 and two simple push buttons that when pressed will toggle the state of one of the relays.  I'll get into the wiring in a bit more detail shortly, but before someone asks, here is the wiring diagram for the test circuit.

Click to enlarge

Note that nothing is connected to the switched/output side of the relays.  Since these relays use isolated circuits, nothing added to the load side will impact the current/voltage on the control side.  Again, I'll get into the Arduino and ESPHome code a bit later, but this is the simple Arduino sketch I'm using for the test:

/* Simple test code to toggle one of two relays (3V vs. 5V)
   based on a button press.  Used to test relay current draw.
*/
#define RELAY_PIN_3V 27
#define RELAY_PIN_5V 26
#define BUTTON_3V 33
#define BUTTON_5V 32

void setup() {
  pinMode(RELAY_PIN_3V, OUTPUT);
  pinMode(RELAY_PIN_5V, OUTPUT);
  pinMode(BUTTON_3V, INPUT_PULLUP);
  pinMode(BUTTON_5V, INPUT_PULLUP);
 
  digitalWrite(RELAY_PIN_3V, LOW);
  digitalWrite(RELAY_PIN_5V, LOW);
  digitalWrite(BUTTON_3V, HIGH);
  digitalWrite(BUTTON_5V, HIGH);
}

void loop() {
  if (!digitalRead(BUTTON_3V)) {
    //Toggle 3V Relay
    if (digitalRead(RELAY_PIN_3V)) {
      digitalWrite(RELAY_PIN_3V, LOW);
    } else {
      digitalWrite(RELAY_PIN_3V, HIGH);
    }
    delay(250);
   }

  if (!digitalRead(BUTTON_5V)) {
    //Toggle 5V Relay
    if (digitalRead(RELAY_PIN_5V)) {
      digitalWrite(RELAY_PIN_5V, LOW);
    } else {
      digitalWrite(RELAY_PIN_5V, HIGH);
    }
    delay(250);
   }
}

Once flashed to the ESP32, I can then use the two buttons to independently toggle the state of each relay.


When both relays are powered on, the multimeters display the current draw.  The 5V relay pulls about 71mA when energized and the 3.3V pulls a much higher 116mA.  This is actually very close to the published specs of 71.4 for the 5V relay and 120mA for the 3V relay.


So, can these be powered directly off the 5V or 3.3V pin of the ESP32?  That depends!  It's really contingent upon the voltage regulator on the ESP32 dev board.  Certain on-board regulators can handle higher current than others.  As a safe bet, assume no more than 500mA can be used by a power pin.  But in the case of the 3.3V pin, this current is shared by the ESP chip itself, which can draw up to 250mA, leaving only 250mA for any connected peripherals.... and if connecting other power-drawing components to the power pin, you could easily exceed the maximum current rating.

So from the initial measurements, either relay could theoretically be powered directly off the 5V or 3.3V as appropriate.  But especially for the 3V relay, it may be wise to consider powering this directly from your 5V power supply via a buck converter.  I'll cover both methods in the following wiring diagrams.


Wiring Diagrams - Control/Input Side


While the wiring diagrams for both the 3V and 5V relay are similar, the GPIO pins on the ESP32 only output 3.3V, we'll need to "shift" or boost the logical data signal up to 5V when using a 5V relay.

5V Relay - Powered via 5V Pin

Click to enlarge

In this scenario, the ESP32 is powered via the 5V USB port and the 5V VIN pin is used to power the relay.  A logic level shifter is used to 'shift' the logic data or control signal from the ESP32's 3.3V to the 5V expected by the relay.  The shifter also needs 3.3V and 5V, but these are sourced from the ESP32's power pins.

5V Relay - Powered from external power source

Click to enlarge

If you have other peripherals and/or the relay draws too much current for the VIN/5V pin of the ESP32, you can power the relay directly from a 5V power source.  This is very similar to the first scenario, but instead of powering the ESP32 from the USB port, a separate 5V power supply is used (amp rating for this supply will depend upon the total current draw of the project).  The 5V and ground from the power supply is split off and separate legs run to the VIN/GND pin of the ESP32 to power it.  A separate leg is run from the power supply to the power pins of the relay. 5V is also split off and fed to the HV side of the logic level shifter.  

If you've done any DIY LED projects with something like WLED, then you may recognize the wiring... it is nearly identical!  Because the LEDs can draw too  much power, the 5V from the power supply is split and run in parallel to the LEDs and the ESP controller.  A logic level shifter is also used in the same manner (however, I no longer recommend these I2C compatible bi-directional shifters for LED projects.  To see why, take a look at this video: Logic Level Shifter & LED Strips: I Got It Wrong). But while these shifters might be recommended for LED projects, they work perfectly well for relays as speed of the data signal is not an issue.

And like LEDs, it is possible that a 5V relay may trigger from a 3.3V signal without shifting.  But it is better... and more reliable... to assure that the relay is receiving a signal at the expected voltage.  Inconsistent results may occur if you try to use 3.3V.

3V Relay - Powered via 3V3 Pin

Click to enlarge

Of all the combinations, a 3V relay powered by the ESP32's 3V3 pin is the simplest wiring.  Since the GPIO data signal is already 3.3V (yes, 3.3V can be used for 3V), there is no need to shift the data signal voltage.  However, on the flip side, this scenario is more likely to approach the current limits on the 3V3 power pin.  This is because this power is shared by the ESP32 itself, which can consume up to 250mA.  This means if the power regulator has a 500mA limit, only 250mA is available for the 3V3 pin use.  Add a couple of other 3.3V peripherals and you are likely to exceed the max current.  Do note that you can also connect a separate power supply to the VIN pin for powering the ESP32 itself, similar to what I'll show next.

3V Relay - Powered from external power source

Click to enlarge

To power the relay separately via a single 5V power supply, the 5V power is once again split.  One leg runs to the VIN/GND pin of the ESP32 to power it.  For a different leg, we have to step the 5V down to 3V for the relay.  To do this, we can use a buck converter.  The one I'm using can step down anywhere from 4.5V-16V to either a consistent 3.3V or 5V.  And this particular buck converter can handle up to 2A, which is more than enough to power the relay.

Again, no logic level shifter is needed for the 3V relay, as the GPIO pins output 3.3V and the relay expects 3V for a HIGH data signal.

Wiring Diagrams - Load/Output Side


This was sort of covered in the pinout sections below.  But depending upon the relay, you may have three different output terminals.


Three terminals allow you to set up the switch-side of the relay as normally-open or normally-closed.  The live or positive leg from the power supply is split across the common and the NO or NC terminal.  When using the NO terminal, the circuit will be off when the relay is off as shown in top example above.  If you use the NC terminal, then the circuit will be on when the relay is off and vice versa.

While technically not necessary, I select the option where the relay will spend the majority of its time in the 'off' state.  In other words using the above photo as an example, if I expect the light to be on a majority of the time, I'd select the NC terminal.  Conversely, if I expect the light to be off more than on, I'd use the NO terminal.  This just reduces the current draw needed to keep the relay energized (and therefore the heat generated and energy used).

Safety Note: The NC/COM terminals are connected any time the relay is off.  This is the normal default setting. Use caution when connecting devices to the NC/COM terminals as the circuit will be "live" even if the relay isn't connected to its own power or a data control signal (unless the relay provides jumpers to change the default behavior - see below).

Switching between Two Circuits

If your relay does offer both NC and NO terminals, you can take advantage of this and use the relay to switch between two different circuits.  Internally, the relay switch acts like a single-pole, double-throw switch.


In effect, when the relay is on or energized, one side of the output circuit will be completed.  When the relay is off, the other side of the output circuit will be enabled.

Relay "off"

Relay "on"

The only caveat here is that both circuits use the same voltage/power supply.  But toggling the relay will also toggle which circuit is live and which is off. 

Most of the examples so far show switching a power circuit.  But the relay can also be used to switch between other types of circuits.


In this example, a relay is used to switch the data line connected to an LED display between two different LED controllers.  WLED might be installed on one controller and another LED application on the other.  Either controller can send its data signal to the LEDs based on the state of the relay.  If you want to see more about this type of relay use, I have two other videos and related blog articles that show the process I used.

Click to launch video


Click to launch video

Related blog: An ESP32 LED Matrix Clock, Scoreboard, Timer and more with FULL WLED


But what if you need to control more than one circuit, but they are different voltages?  Of course you could use more than one relay or you could simply purchase a multi-channel relay.


You can find 3V and 5V relays (and others) in multi-channel versions such as 2 relays, 4 relays or even 8 relays.  While these combine multiple relays into a single board, they are controlled in the same manner... each relay has its own GPIO pin and can be independently operated.  But most use a single power supply/source for powering the 5V or 3V relay.  As such, remember that each relay will draw current when energized (per above discussion) so you must assure that the power supply can support energizing multiple relays.  For example, from above, we know that each relay in the 5V version can draw up to 71mA.  If using an 8-channel relay and all relays were energized at the same time, that could pull well over 500mA of power... definitely not a board to try powering from the 5V pin of the ESP32!  Just assure your power supply can provide the necessary current when using multi-channel relay boards.

This article will focus on single channel relays but the info provided can easily be adapted to multi-channel relays.

Jumpers and Other Options


Depending upon the relay you are using, jumpers may be provided to change how the relay operates. You may need to refer to the relay's documentation, but here are the jumpers on the relays I'm using.

3V Relay Jumpers


This 3V relay has two jumpers.  All these relays do is connect the VCC and/or GND terminals to the relay's power pins.  Normally you'd leave both jumpers installed and use the terminals for VCC and GND connections.  However, if you have a special need, you can remove one or both jumpers and supply power directly to the relay itself.  This would really be a corner case and in most situations, you'd just leave the jumpers as they are.

5V Relay Jumpers


This particular 5V relay has a single jumper.  This jumper determines whether the relay is energized (turned on) when it receives a logic high or low signal from the controller.  When the jumper set to low (L) as shown above, you'd send a LOW or 0V signal to turn the relay on and HIGH to turn it off:

digitalWrite(RELAY_GPIO, LOW);  //Turns relay ON
digitalWrite(RELAY_GPIO, HIGH); //Turns relay OFF

Conversely, if the jumper is set to high (H) then the opposite commands would be used to toggle the relay:

digitalWrite(RELAY_GPIO, HIGH);  //Turns relay ON
digitalWrite(RELAY_GPIO, LOW); //Turns relay OFF

If you find that your relay is operating backwards from what you'd expect, see if there is a jumper that controls the trigger level and switch it to the other setting.

Other relays from other sellers may have different jumpers or options (or none at all).  Again, check your relay's documentation.

Controlling a Relay


The code or firmware needed to control a relay is very simple.  Since the relay is controlled by a single GPIO pin and all that needs to be done to toggle the relay's state is to toggle the state of the GPIO pin.  No special libraries or configuration is needed.

Arduino

To use a relay in Arduino/C++, all that needs to be done is to define the GPIO output pin. The relay can then be toggled by setting this pin to LOW or HIGH.

#define RELAY_PIN 27   //Relay connected to GPIO27

void setup() {
  pinMode(RELAY_PIN, OUTPUT);
     
}

void loop() {
  if ("some condition exists") {
    //Turn relay ON
    digitalWrite(RELAY_PIN, HIGH);

  } else {
    //Turn relay OFF
    digitalWrite(RELAY_PIN, LOW);
  }
}

If you are using the NC terminals on the relay, the relay has a jumper setting to trigger on LOW or the relay otherwise operates backwards from desired, you can simply flip the HIGH and LOW settings above.  But that's really all you need to control a relay from Arduino.

ESPHome

ESPHome is even easier than Arduino!  All we have to do is define a GPIO switch.

# Example configuration entry
switch:
  - platform: gpio
    pin: GPIO27
    name: "My Relay"


That's it!  When integrated into Home Assistant, a new switch entity will be created.  Toggling the switch will also toggle the state of the relay... and therefore the circuit it is controlling.  Note that ESPHome has many additional switch parameters and settings (see links at end of this article).  In addition, automations can be executed within the ESPHome module so if you have other peripherals connected to your ESP32, say such as a motion or presence detector, you can trigger the relay based on the detected state... all in ESPHome without any external automation engines.

Home Assistant and Automations


Of course if you are building your own ESP32 DIY project that uses a relay, you are likely going to want to automate it in some manner and maybe add it to a dashboard for direct control.


If you are using ESPHome for your project, then ESPHome natively integrates into Home Assistant and a switch entity will be created as shown on the top above.  Toggling the switch via dashboard, automation or script will toggle the state of the relay.

If building your project and firmware with something like Arduino/C++ or Python then you could use something like MQTT to establish communication between Home Assistant and your device and then control it like any other native switch entity in Home Assistant as shown on the bottom above.  Using MQTT is beyond the scope of this article, but I have a series of videos on using MQTT in my YouTube Home Assistant Playlist.  The videos cover the basics of MQTT including what it is and how it works, how to create MQTT entities in Home Assistant and how to add MQTT to your Arduino or Python project.

Wrap Up


While commercial devices like smart plugs offer a convenient way to control power to other devices, they are limited to the features provided by the manufacturer and may also require a cloud account or (gasp!) a subscription to fully use.  Do note that there are some commercial devices that provide local control via options like MQTT or even come preinstalled with local firmware like Tasmota or ESPHome.

But relays are actually one of the easiest peripherals to wire and control via an ESP32 (or other type of MCU). And unlike many smart plugs (and switches), you aren't limited to switching an 120V/240V AC circuit.  As shown, you can switch pretty much any circuit with the relay's specifications... even something like a data line.  And you have complete control over how the relay works and operates, including adding additional peripherals to the ESP32.

If you've ever wished you could control a circuit with your ESP32, then a relay may be the answer you've been looking for!  Let me know down in the comments if you have questions or found unique uses for relays in your own projects.  Thanks for reading!

Links and Additional Info



Supporting this blog and related YouTube channel


It takes significant time and effort (and often expense) to create these articles and videos.  If you'd like to support future content on this blog and the related YouTube channel, or just say thanks for something that helped you out, you can consider buying me a one-off cup of coffee or two at:


No comments:

Post a Comment

To help eliminate spam and to keep all conversations civil, submitted comments are moderated. Therefore your post may not show up immediately. Please be patient as most reviews are completed within a few hours.