Intro: How Does It Work: DIY Relay Modules
After looking through many instructables it's clear that many makers love to use the pre-assembled relay modules to switch large loads or mains voltages using their Raspberry Pi or Arduino. These can be bought from places like eBay for as little as £2. There's many tutorials on how to use them with your microcontroller, and even how to make your own. But none explain in detail how it works, the importance of each component or why a particular value was selected.
In this instructable I wanted to show you how you can easily make your own module and how to calculate the correct component values. A word of warning, working with mains electricity is dangerous and can be deadly. Although it is possible, I do not recommend using a home made module for switching mains voltage
Step 1: Tools & Components
Before we start check you have the following
- Soldering iron
- Solder flux
- stripboard track cutter (a small drill bit will also work)
- Tinned copper wire <1mm diameter
- Side cutters
- Craft knife
- Multimeter (for measurement and troubleshooting)
- 2.54mm stripboard
- 2N3904 general purpose transistor (most transistors will work as long as you make sure the collector current is enough to drive the coil of the relay. In our case at least 60mA).
- 12V Relay, 16A contacts
- PC817 Opto-coupler
- PCB screw terminals
- Resistors (1k Ohm, 270 Ohm)
- 1N4007 diode
- Male header/Jumper pins
The following isnt madatory but it will help you build the schematic on a Breadboard. If your not interested you can skip that step and go straight to soldering.
- Solderless breadboard
- Dupont / Jumper wires
- Momentary push button switch
- Seperate 12v and 5v supply (I will use a standard DC "wall wart" and my benchtop supply)
Step 2: Circuit Schematic & Theory of Operation
OK take a deep breath....were going to take a deep dive into the theory of how the whole thing works. I didnt realise there was so much until I got about 70% of the way through writing the thing.
The module I am making here is active high. This means when "IN1" in our schematic is high (i.e. 5V from an Arduino) it activates the relay module. The pre-fabbed modules are usually active low where "IN1" in our schematic is tied to 5V and ground of the optocoupler is used as IN1 instead.
So how does this work? Lets start with the optocoupler. The optocoupler provides galvanic isolation and is there to prevent potentially catastrophic voltages flowing back through the device and reaching your microcontroller in the event of a fault. Essentially it separates the "relay side" from the "controller side", and you may notice there are no physical connections between the two sides. Instead there is an diode symbol with some arrows pointing to the base of a transistor, this indicates that the diode is a LED (light emitting diode) and the transistor is a photo-transistor. Unlike a regular transistor, the base of the photo-transistor is sensitive to light and will conduct (or switch on) between it's collector and emitter when light saturates its. When IN1 is high current can flow from IN1 through the current limiting resistor R1, the LED, and back to ground.
Just like any conventional LED a resistor is needed to limit the current to the correct value in the datasheet and stop the LED burning out. These values are easily calculated using Ohm's law, usually LED's have a current requirement of 20mA, and at 5V this is equal to...
V/I = R
5 / 0.02 = 250 Ohms (the closest resistor value is 270 Ohms)
The internal LED of the optocoupler now illuminates saturating the base of the photo-transistor thus allowing current to flow from JDVCC through the optocouplers photo-transistor, and through to the next part of our circuit. Going forward this voltage will determine our resistor values.
R2 is necessary because it limits the base current of Q1 which stops it sourcing more current than it can handle, but it also sets the current gain of the transistor. Transistors can be used as current amplifiers, meaning that the current at the base will be amplified at the collector by a factor given in the datasheet. This is known as GAIN, hFE or Beta and is a ratio usually in the hundreds. Beta is the ratio of collector curent (Ic) to base current (Ib) so we can select a resistor to limit the base current to a suitable value. The equation for gain is simply..
Beta = Ic / Ib
Beta = 100mA / 1mA = 100
Why do we need to amplify the current? Because the current required to energise the relay's coil will be around 60mA according to its datasheet (much more than the 20mA available from a RPi or Arduino). Looking in the datasheet for Q1 we can see a Ic of 100mA and a typical gain of 100. Which means the base current must be limited to between to 100 times less (i.e. 1mA ).
Using ohms law yields...
V / I = R
12 / 0.001 = 12,000 Ohms (12k Ohms)
Theoretically this is correct but Beta varies with different base currents. The datasheet claims a minimum of Beta = 30 for a collector current of 100mA, so the base current in this instance should be 100mA / 30 = 3.3mA. If we use ohms law again to calculate our resistor value for 3.3mA we yield 3.6k Ohms. To add further complexity, we want our transistor to be fully saturated (i.e. fully "on" to ensure our relay activates) which requires 5mA in the datasheet, which in fact would require a resistor of 2.4k Ohms.
Confused much? Which value should we use for our base resistor (Rb)? Well we can demonstrate these components using simulation software. I setup a test circuit with a simulation package and tested all four resistor values. The attached pictures show a test circuit the different base resistors. On the bottom right the 12k resistor which has a gain of 109mA / 0.932mA = 116.9. The bottom left 3.6k resistor with gain = 237mA / 3.09mA = 76.6. The top right 2.2k resistor, with gain 397 / 7.3 = 63.1, and just for fun a 1.5k Ohm resistor with gain = 53. On review it looks like the 2.2k Ohm resistor is a good value for Rb because it gives a base current of almost exactly 5mA.
Finally, once the base of Q1 is saturated it will conduct through its collector-emitter path and switch on the relay in our schematic. The diode D1 is placed across the contact points of the relay, as a protective measure from back EMF (electromotive force). The reason is because, as the coil in the relay becomes active it stores energy in the form of magnetic flux (MMF magneto motive force) surrounding it. When the module switches off and the relay loses its driving current, the MMF collapses and is induced back into the coil as EMF flowing back into the circuit. Without the diode this large back EMF would destroy the circuit. The diode is sometimes called a "quenching" or "flywheel" diode because it prevents the flow of current back into the circuit. You may notice that the diode points upwards? This is known as reverse bias, and means that current can only flow in one direction.
That pretty much covers the theory.
Step 3: Measure Your Components
It's not mandatory but I like to check the critical components to make sure they are the values they claim to be. It is possible to buy counterfeit or fake goods or simply that you might of received a component from a faulty batch. This doesn't happen often but it's always good to check :-)
I wanted to confirm the current draw on the coil of the relay so I powered it up using 12 volts from my benchtop power supply and monitored the Current draw with a multimeter (you can see the multimeter has a better accuracy than the power supply's display). I recorded a Current of just under 40mA.
If your multimeter has a transistor tester like this one you can check the gain. Just turn the rotary knob it "hFE" and put the transistor into the slot on the front that says "NPN". Make sure you put the legs of the transistor in the correct holes. The base goes into "B", the emitter into "E" and collector into "C". I have attached a pictorial from the datasheet, notice the flat side of the package? this will help you identify the pins. By the way, the symbol for an NPN transistor always have the arrow pointing outwards and PNP points inwards. On this occasion I measured the transistor to have a gain of 347 (take this with a pinch of salt, the measurement simply validates that the transistor works). As we discussed in the previous step gain can be tricky. (If you are interested in seeing an instructable about this let me know in the comments and I can put something more comprehensive together!).
Simply put one probe on each end of the legs of the resistor and read the value off the DMM...easy! Depending on what type of resistors you buy the values may not be spot on but should be within a good tolerance. For example, a 1k Ohm resistor should be within plus or minus 1% of its intended value (999 to 1001). If this was 5% this would mean 952 to 1050 ohms, not so good.
Not all DMM's have diode checkers but if yours does you can at least check it works, and you multimeter will tell you its switch point. In my case the 1N4007 conducts at 0.5534V, not critical for our application but I was expecting it to be between 0.63V to 0.7V
The only way I know how to test this properly is on a breadboard. At this point you may want to start assembling the schematic on a breadboard to see if all the parts work correctly. So in the next step I will show you how to assemble this on a breadboard.
Step 4: Assembly
To emulate the application of a signal from a GPIO pin of a micro controller I used a SPST momentary push button to activate the 5V side. I've marked on the photo where the 12V and 5V rails come into the breadboard. During assembly and testing I notice that the 2.2k base resistor I calculated for the base of the transistor was too high and the transistor wasn't switching the relay correctly. I found that a value of 1.8k or lower was sufficient to make the circuit work correctly. In my Breadboard you can see two resistors in series to make 1.5k Ohm (1k Ohm and 500 Ohm) but I can confirm a 1k resistor will work fine as well.
in summary our final component list is as follows:
R1 - 270R
R2 - 1k
Q1 - 2N3904 NPN transistor
D1 - 1N4007 diode
IC - PC817 optocoupler
Relay - Coil 12V, 40mA. Contacts - 250Vac 16A max
Halfway through soldering on the relay I made a mistake so had to start again (that's why the relay is a different colour in the later pictures lol). Soldering takes practice, I'd suggest playing with the layout before committing to solder anything down permanently. Start with the larger components and then followed by the smaller ones. My technique is to use a little bit of masking tape to hold the component on the white side of the stripboard while I solder the tracks on the bottom that way they don't move around (some people like to bend the legs of the components, but I find they still flap around a bit when moving the board). If you need to solder more than one component on the same track that isn't meant to be connected make sure to use a track cutter to separate the tracks.
Step 5: Final Testing
Once you have completed the build, hook up a 12v supply for the relay and 5v supply for your Arduino. I uploaded the "Blink" sketch and pulsed pin 7 on the Arduino Uno just as a test. Success! You have finished your relay module and hopefully learnt a little bit about how it works.
It's hard putting into words absolutely everything when writing an instructable. I find when learning something new it always helps to watch alot of videos. Here are some videos which will really help.
Calculating the correct value of Rb for a transistor
Using the Relay module
Measuring hFE / Current gain of a transistor