Detecting and controlling mains voltages with a Raspberry Pi or Arduino

Experiments using a Raspberry Pi and solid state relays (SSRs) to sense the presence of mains electricity and switch loads on/off.

View on GitHub

By Paulo Ferreira de Castro (LinkedIn, GitHub), July 2022


This article is hosted by GitHub Pages at: https://pdcastro.github.io/mains-io
If you are reading the markdown source, check the hosted site for a better experience!



Introduction

Recently I found myself searching the web for a convenient way of using the Raspberry Pi’s GPIO pins to detect/sense and control/switch mains voltages (100V to 240V AC): simple binary on/off sensing and switching.

Objective: Sense a mains voltage signal (input) and control a mains voltage load (output).

Some search results suggested using current clamps, current transducers or other current sensors. But I needed to detect a mains voltage, not current, as if detecting that a cable was energized by the flick of a switch without any load connected to it (other than the sensor itself).

Other search results suggested connecting a USB charger to the mains voltage being detected, and using resistors to reduce the 5V output to 3.3V as required by the Pi’s GPIO pins. An issue with this solution is that it can take several seconds for the 5V output to turn off when the mains voltage signal is turned off, which may be too long a delay for some applications.

Yet other results pointed to using electromechanical relays or optocoupler / optoisolator microchips, alongside circuit diagrams and even PCB (Printed Circuit Board) layouts for the reader to build their own board.

Those are valid solutions, but I was hoping to find ready-made “small boxes” that minimized exposed circuit boards and that I could wire directly to the Raspberry Pi without additional components like resistors or diodes.

Digging further, I came across solid state relays, or SSRs for short, which turned out to be a great fit for my project. These are essentially the ready-made units I was hoping to find: the right ones can be wired directly to the Raspberry Pi. SSRs enclose electronic circuits based on optocoupler microchips, with convenient form factors such DIN rail mounts or screw terminal sockets. There are a few different technologies of SSRs to choose from, such as thyristor/TRIAC, MOSFET or bipolar transistors, with differences in cost and suitability.

In this article I share the results of some experiments with a few SSRs, which hopefully will save you some time figuring out the best solution for your own projects.

Three of the five SSRs used in the experiments.

Safety first

MAINS ELECTRICITY ACCIDENTS MAY KILL YOU AND DESTROY YOUR PROPERTY.

This article is aimed at competent individuals with experience working with electrical circuits, who can fully make sense of the information provided.

Please check the important safety and disclaimer notes at the end of the article.

Solid state relays vs. electromechanical relays

Relays
Left: an electromechanical relay. Middle and right: solid state relays.

Like an electromechanical relay, an SSR has two sides:

  1. Input or Control or Coil side.
  2. Output or Load or Contact or Switching side.

Also like electromechanical relays, these two sides are galvanically isolated from each other, i.e. there is no continuity path for an electrical current between the two sides. Electromechanical relays produce a magnetic field in the control side to move metal contacts in the load side, while SSRs emit light in the control side to switch semiconductor junctions on/off in the load side (built-in optocoupler microchips).

Despite this physical difference, SSR datasheets often use the terms “coil” and “contact” to refer to the two sides of an SSR as well, drawing a clear parallel with electromechanical relays.

Some pros and cons of SSRs compared to electromagnetic relays:

Pros of SSRs

For an example of the last point, the datasheet of the popular Relpol RM84 series of miniature relays specifies:

Min. switching voltage: 5V (AgNi), 5V (AgNi/Au hard gold plating), 10V (AgSnO2)
Min. switching current: 5mA (AgNi), 2mA (AgNi/Au hard gold plating), 10mA (AgSnO2)

The Raspberry Pi’s GPIO pins use 3.3V and internal 50KΩ pull-down and pull-up resistors that draw only 0.07mA, thus meeting neither the voltage nor the current requirements above. I had a hard time trying to find electromechanical relays with a coil rated for mains voltages and better (lower) minimum load-side contact voltage and current ratings, while suitable SSRs were easier to find.

Cons of SSRs

Choosing the right SSR

The load side of an SSR consists of semiconductors that come in a few flavours to choose from:

SSR load-side semiconductor Load type Off-state leak current Cost
Thyristor / TRIAC AC (alternate current) Higher (e.g. 1mA) Lower
Bipolar junction transistor (BJT) DC (direct current) Lower (e.g. 10μA) Lower
MOSFET transistor Both AC and DC Lower (e.g. 10μA) Higher
Schematic symbols of SSRs of different technologies.

The ability to handle AC or DC loads is a clear-cut difference. A more subtle distinction is the off-state leak current that, as I found out, may have side effects beyond a small energy waste, such as humming noises or light bulb flashing as described in the experiment results below.

SSR application: mains voltage sensor

To detect mains voltages (on/off binary sensor), the idea is to connect the control side of an SSR to the mains voltage signal to be detected, as shown in the figure below. The load side is connected to two pins of the Raspberry Pi header: 3.3V supply, and a GPIO pin configured by software as input with an internal pull down resistor (internal to the Raspberry Pi).

Mains voltage sensor connections using a suitable BJT SSR.

In this application, the SSR control side should be rated for mains voltages (e.g. 240V AC, rms), and the load side rated for low DC voltages including 3.3V DC (typically a range such as 3V DC to 24V DC). The SSR’s load side technology will typically be a MOSFET or bipolar junction transistor (BJT). The voltage drop on the transistor will typically be lower than 1V. The Raspberry Pi interprets voltages higher than 1.8V (ideally 3.3V) as logical 1, and lower than 1.8V (ideally 0V) as logical 0. If the voltage drop was as high as 1V, it should still be OK as 3.3V - 1V = 2.3V = logical 1.

For my mains voltage sensing experiments, I sourced two SSR units: the IDEC RV8S-L-D48-A240 from Digikey and the Wago 857-708 from BPX. Both are based on a bipolar transistor on the load side that can be wired directly to the header pins of a Raspberry Pi, both have DIN rail sockets and benefit from an indicator LED on the control side. See photos in the Introduction and Putting it all together sections.

⚠ Attention!
The datasheets of both SSRs specify a maximum load-side current of 100mA. Even at low voltages, either the SSRs or the Raspberry Pi could get damaged if wired incorrectly, for example if the load side was wired to 0V and 5V pins which would effectively mean a short circuit that could draw more than 100mA. If wired correctly to two GPIO pins, a software bug could still cause a short circuit if the two GPIO pins were configured as outputs, one pin at 0V and the other at 3.3V. In this case, however, I expect that the Raspberry Pi would supply a maximum current of around 16mA (based on some web search results — not tested), which would not damage the SSR but could possibly damage the Raspberry Pi if this maximum current was drawn for an extended period of time.

The table below gathers some current and voltage measurements with a digital multimeter.

Parameter Load (3.3V DC) IDEC RV8S-L-D48-A240 Wago 857-708
Control/coil current at 240V rms, 50Hz (lower is better) Any 8.5mA rms 3.5mA rms
Control/coil power consumption at 240V rms, 50Hz (lower is better) Any 2W 0.8W
On-state* voltage drop, load side (lower is better) 47KΩ resistor** (0.07mA DC) 0.21V DC 0.12V DC
On-state* voltage drop, load side (lower is better) 100Ω resistor (25mA DC) 0.79V DC 0.72V DC
* "On state" means that the SSR was turned on with mains voltage applied to the control side. The voltage drop is on the relay terminals, load side.
** A 47KΩ resistor load simulates the Raspberry Pi's internal 50KΩ pull-down / pull-up resistor (configurable by software).

The winner

The Wago unit was a clear winner in all metrics, but especially for running less hot. The 2W consumed by the control side of the IDEC unit (even when no load is connected) results in the unit getting very hot to the touch after a few minutes in the ‘on’ state: Holding it at the warmest spot for more than a few seconds would burn my fingers. The heat comes from an internal voltage drop resistor. The Wago unit wastes “only” 0.8W by using high efficiency LEDs that draw less current; it got warm to the touch, but not hot like the IDEC unit and OK to hold without burning one’s fingers. Even better designs would be possible if the SSR internally used a high-gain optocoupler microchip like the Broadcom HCPL-4701 that requires only 40μA in the control side. This would allow the SSR to consume e.g. 0.02W instead of 2W or 0.8W, and run cooler.

SSR application: mains voltage switch

This is the more common use of relays: a low-voltage control side connected to the Raspberry Pi, and the load side connected to a mains-voltage AC load (e.g. light bulb, electric motor, room heater, etc.). The control side is connected to two pins from the Raspberry Pi header: GND, and a GPIO pin configured as output, producing 3.3V as logic 1 and 0V as logic 0. The connections are illustrated in the figures below.

Circuit for a TRIAC SSR with a built-in control-side LED driver rated for 3.3V DC, such as the LinkFreely TRA23D10 or the LDG MRA-23D2 SSRs.
Circuit for a generic MOSFET SSR with a built-in control-side LED driver rated for 3.3V DC.
Circuit for the CPC1984Y MOSFET SSR with an external 330Ω resistor.

For my mains voltage switching experiments, I sourced three SSR units: the LinkFreely TRA23D10 and the LDG MRA-23D2 from AliExpress, both cheap-ish TRIAC-based units in DIN rail mounts, and the IXYS CPC1984Y MOSFET SSR in a 4-pin SIP package from Digikey. See photos in the Introduction and Putting it all together sections.

The first two units are supplied in DIN rail packages with screw terminals and do not require external components (resistor). The CPC1984Y requires an external resistor and assembling in a PCB or perfboard. As such, it does not meet my initial requirement of being a “ready-made small box, without an exposed PCB, that could be wired directly to the Raspberry Pi without additional components”. If a PCB is needed, one might as well add a driver circuit for the coil of an electromechanical relay instead of using an SSR (depending on the application). Indeed I only included the CPC1984Y in my experiments when I realized that the other SSRs I had were not able to cope with a mains-voltage LED light bulb load as explained below, and I was curious whether a low-leak-current MOSFET SSR would solve the problem. Sadly, I could not find any MOSFET SSR model in a more convenient form factor, at least not one under USD $30 and preferably with a DIN rail socket. If you find one, let me know!

The table below gathers some current and voltage measurements with a digital multimeter.

Parameter Load (240V rms) LinkFreely TRA23D10 (TRIAC) LDG MRA-23D2 (TRIAC) IXYS CPC1984Y (MOSFET)
Control/coil current at 3.3V DC (lower is better) Any 6.1mA DC 6.6mA DC 5.6mA DC (external 330Ω resistor)
Control/coil current at 5.2V DC (lower is better) Any 8.5mA DC 9.7mA DC 8.0mA DC (external 470Ω resistor)
On-state* voltage drop, load side (lower is better) 3W mains-voltage LED light bulb 1.17V rms 1.06V rms 0.04V rms
42W halogen light bulb 0.99V rms 0.93V rms 0.09V rms
60W water pump motor 1.00V rms 0.93V rms 0.11V rms
1.5KW resistive heater 1.05V rms - -
Off-state** leak current, load side (lower is better) 3W mains-voltage LED light bulb 0.66mA rms 0.92mA rms 0.01mA rms
42W halogen light bulb 0.69mA rms 1.01mA rms 0.01mA rms
60W water pump motor 0.69mA rms 1.01mA rms 0.01mA rms
1.5KW resistive heater 0.69mA rms - -
* "On state" means that the SSR was turned on with 3.3V DC applied to the control side. The voltage drop is on the relay terminals, load side.
** "Off state" means that the SSR was turned off by having the control side disconnected.

The most interesting finding was a misbehavior when the load was a 3W mains-voltage LED light bulb (Edison screw cap), with a built-in LED driver. When the SSR was turned off (control side disconnected), the TRA23D10 and the MRA-23D2 TRIAC SSRs caused the light bulb to flash at around 2Hz rather than properly turn off, as shown in the short video below. When the SSRs were turned on, the light bulb correctly shone at full brightness. I tested two further mains-voltage LED light bulbs that also misbehaved in the off state, though rather than flashing, they would either produce a noticeable hum noise, or shine at low brightness. Flashing, humming, or low shining — it is not what you want when the light bulb is supposed to be turned off!

Video: Some SSRs cause the LED light bulb to flash when it should be turned off.

I believe the cause is the relatively high off-state leak current of the TRA23D10 and the MRA-23D2 SSRs, that affects the built-in driver circuit of the mains-voltage LED light bulb. At least in the case where the light bulb flashed, the LED driver probably contained a rectifying bridge that charged a capacitor. A leak current nearing 1mA would be sufficient to charge that capacitor in less than a second, at which point the light bulb emitted a flash that discharged the capacitor and restarted the cycle. This is just a theory though.

This misbehavior did not happen with the IXYS CPC1984Y MOSFET SSR. I believe this is because the leak current was about 100x lower than the TRIAC models (1mA vs. 0.01mA). Such a low current would be comparable to the self-discharge current of the LED driver capacitor, not allowing the capacitor to charge to the point of causing flashing or noticeable humming or shining.

Whatever the explanation, the observed fact is that the selected MOSFET SSR did a good practical job of turning on and off all of the tested load types, while the selected TRIAC SSRs were not able to handle the mains-voltage LED light bulb.

All three SSRs did a good job with the other load types (halogen bulb, pump motor, resistive heater) in either ‘on’ or ‘off’ states: no noticeable humming or shining.

Energy loss/waste as heat

Regarding energy loss / waste heat, the following table provides some calculations. The on-state heat loss in the SSR, in watts, was calculated by multiplying the the voltage drop at the SSR terminals (given in the previous table) by the load current. The load current, in turn, was calculated as the load power divided by 240V rms (my mains voltage). In the off state, we are interested in the sum of dissipated power over both the load and the SSR. Therefore, it was calculated by multiplying the SSR leak current (given in the previous table) by the mains voltage of 240V rms.

Parameter Load (240V rms) LinkFreely TRA23D10 (TRIAC) LDG MRA-23D2 (TRIAC) IXYS CPC1984Y (MOSFET)
On-state* heat loss in the SSR, in watts. In brackets, relative value as a percentage of the load power. 3W mains-voltage LED light bulb 0.01W (0.49%) 0.01W (0.44%) 0.001W (0.02%)
42W halogen light bulb 0.17W (0.41%) 0.16W (0.39%) 0.02W (0.04%)
60W water pump motor 0.25W (0.42%) 0.23W (0.39%) 0.03W (0.05%)
1.5KW resistive heater 6.5W (0.44%) - -
Total off-state** heat loss over the SSR and the load, in watts. In brackets, relative value as a percentage of the load power. 3W mains-voltage LED light bulb 0.16W (5.3%) 0.22W (7.4%) 0.002W (0.08%)
42W halogen light bulb 0.17W (0.39%) 0.24W (0.58%) 0.002W (0.006%)
60W water pump motor 0.17W (0.28%) 0.24W (0.40%) 0.002W (0.004%)
1.5KW resistive heater 0.17W (0.01%) - -
* "On state" means that the SSR was turned on with 3.3V DC applied to the control side.
** "Off state" means that the SSR was turned off by having the control side disconnected.

If the mains voltage was, say, 120V rms instead of 240V rms and the loads were of the same power, the load current would double and the on-state heat losses would double as well (both absolute and relative). Indeed, the current for a 1.5KW heater would double from 6.25A to 12.5A and would exceed the 10A maximum rating of the TRA23D10. (By the way, even at 6.25A, one should consider SSR models with good heat dissipators for safer operation.) In the off state, I am not sure if the leak currents would remain the same but at least I expect they would not be any higher. If they remained the same, the off-state losses would halve (both absolute and relative) compared to the values in the table above.

The winner

The IXYS CPC1984Y MOSFET SSR was a winner across all measured parameters, however the comparison is not quite fair because:

Another interesting observation about the IXYS CPC1984Y MOSFET SSR is that the measured leak current of 10μA (0.01mA), although quite low, is actually 10 times higher than the datasheet specification, which is 1μA maximum. I measured it both directly through a multimeter, and indirectly through the voltage drop on a 100KΩ resistor used as the load: 1.1V / 100KΩ = 11μA rms. Whether 10μA or 11μA, it is clearly more than the 1μA promised in the CPC1984Y datasheet for temperatures of up to 85ºC (185ºF) (the device was actually cooler than my finger). Maybe I was unlucky and got a defective unit, or somehow managed to damage it, but it is also an odd coincidence that the datasheets of comparable units from other manufacturers (comparable in shape, load ratings and price), such as the Panasonic PhotoMOS Power series, specify leak currents of 10μA — just what I measured.

Putting it all together: DIN rails

Connecting the Raspberry Pi to relays, breakout boards or custom PCBs can result in a fair amount or wiring. When mains voltages are involved, it is especially important that components are firmly attached to avoid wires being pulled out. A final assembly might involve screwing or gluing components to a plastic enclosure, but while testing and prototyping, a more flexible solution is beneficial. I have recently rediscovered the good old DIN rail and cheap plastic brackets on AliExpress that I successfully used to attach two common Raspberry Pi cases to the rail — see photos. There are also Pi enclosures specifically designed for DIN rails, but I found them to be on the pricey side. Rails can be purchased pre-cut to severals lengths from 10cm to 1m, made of steel or aluminum, and many come with pre-drilled holes that make it easier to attach the rails themselves to a plastic enclosure, wooden panel or the walls of a wiring cabinet. Most of the SSRs mentioned in this article come with DIN rail mounts. Power sockets, fuses, RCD / RCBO devices, switches, and so on can also be found with DIN rail mounts. There are also “plug-in screw terminal blocks”, like these, that have two detachable sides (socket and plug) that allow a whole project mounted on a DIN rail to be moved between a workbench and a field location during prototyping.

A prototype project assembled on a DIN rail, including plug-in screw terminal blocks (green, left), a Raspberry Pi and several relays.
DIN rail brackets screwed to a common Pi 4 case.
DIN rail brackets screwed to a common Pi 2 case.

Software

While this article focuses on hardware, I put together some lines of code to monitor a GPIO input pin and copy its state to an output pin, in order to fully test the SSR integration with a Raspberry Pi. An SSR operating as a mains voltage sensor can be connected to the input pin, and an SSR operating as a mains voltage switch can be connected to the output pin, as shown in a photo in the Introduction section. More details can be found in the GitHub repo’s README document.

Important safety notes

Disclaimer

The information in this article is provided without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the author be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the information in this article or the use or other dealings in it.

Discussion

Leave your comments below, or head straight to the repo’s Discussions section. There is also a thread in the Raspberry Pi forums.

If you liked this article, give the source repo a star on GitHub!
Star




Cookies and web traffic monitoring
This page uses Clicky’s privacy-friendly web traffic monitoring service that does not use tracking cookies. The Discussion section is powered by giscuss.app and the GitHub Discussions API that may set their own cookies that are essential to the feature of posting comments.