Working with relays

relay

SparkFun’s latest tutorial shows you how to work with relays. A relay is an electrically operated switch. In this case, they’re using it to switch a 120V AC outlet. The article carries the standard warnings about how not to kill yourself with AC (plus some non sequitor linking throughout). As an extra precaution, they chose a GFI outlet. You probably know how a relay works, but it’s worth seeing how they implemented it. They use a transistor to prevent overloading the microcontroller’s GPIO pin. The control pin is pulled to ground to keep the relay off. A diode is placed across the relay coil to manage the power flow when it discharges. An indicator LED is included to show when the relay closes. This is a great foundation for an automation project, or maybe you just want to terrorize your cat.

Comments

  1. strider_mt2k says:

    I love relays!
    People dis them because they are electromechanical and thus “old school”, but sometimes they are easier to work with than semiconductor equivalents when it comes to bare bones H-bridge stuff for control small robots and RC platforms and such.

    My old wheeled ROV’s drive motors ran so slowly there was no need for speed control at all -just forward backward and stop.
    -all done with relays.

  2. mike says:

    Relays do have their place in the world, there’s no doubting it. and they sound cool when you get a whole bunch of them all opening and closing at random, that chattering sound is neat.

  3. mandy says:

    the diode across the coil is to prevent the back emf spike zapping the electronics driving the relay when the coil is switched off.

    all relays need a diode, sometimes they are built in.

  4. Dave says:

    mandy- that’s not true. They work fine without a diode. They just release a wicked spike when you release them (collapsing magnetic field through a coil = back emf, as you pointed out). This can fry your static sensitive electronics.

    A good place to find a whole bunch of relays without diodes is in a mid 70’s (or before) pinball machine. There’s no processors in there to zap, so there’s no diodes.

    • Brett says:

      You need the diode across semi-conductors, not just the static-sensitive ones. Any device in fact that can be destroyed by a high (albeit brief) reverse voltage. When that field collapses it can be several hundred volts – well and truly enough to kill an 80-100V transistor. I would use a diode as a standard precaution in any circuit.

  5. Dave says:

    Speaking of which- guys, could you be any more confusing in the summary text?

    Please note that changing the uproc output to hi-Z will also allow the relay to switch off. Only a logic ‘1’ on the control pin will turn it on.

  6. I love relays… definitly great for robotics.. converting from a transistor based switch to a relay based switch allowed me to win a robotics competition (automated RC car) in college. I wanted the motor at full speed all the time because my steering algorithm was fast enough to keep up… the relay allowed me to use a short and direct connection from the battery to the motor allowing my car to go faster than all the others.

    There’s something to be said for simplicity, and there’s nothing wrong with using electro-mechancal switches in an electro-mechanical device.

  7. henk says:

    Working with relays?

    ONOEZ!

    What’s next, how to screw in a lightbulb?

  8. Betterer says:

    Maybe use use of a optocoupler in place of the transistor would increase safety and isolate the voltages a little better

  9. Mythgarr says:

    Perhaps this is the overly cautious side of me, but wouldn’t it be a good idea to use, say, an optoisolator rather than a transistor? Cost is pretty low (couple of quarters at mouser) and you get complete electrical isolation between your high-voltage AC line and your very low voltage CMOS/TTL/special flavor of the month components.

  10. pokey says:

    @mythgarr: Isn’t the relay’s purpose to provide air-gap isolation between the low voltage and high voltage/high current circuits?

  11. rusty says:

    I figured this had been done, pretty damn sweet.

    http://web.cecs.pdx.edu/~harry/Relay/

  12. J says:

    I was just trying to learn how to do this yesterday/

    I am so fucking happy right now.

    This + arduino + basic program = 80$ cyclic timer for like 50$ tops…. free if parts scavenged@!

  13. adam says:

    One of my favorite memories from when I first became interested in technology is when I went with my dad, an elevator mechanic, to a job site where the controller room was full of massive banks of relays. As the elevators moved throughout the building you heard a symphony of clicks and clacks which was awesome to my young ears.

  14. Colin says:

    @Adam: That sounds pretty cool. I wish electronics were more ‘physically observable’ like that. It seems so much cooler that way, instead of just a bunch of silent electrons doing their business. Those smug electrons.

  15. Marco says:

    The flyback diode is nice to protect your semiconductors, but if I am not mistaken you might also want to add an RC element in parallel to protect your relays from arcing.

  16. strider_mt2k says:

    I’m still waiting for that definitive list of what kind of stuff exactly is too elementary to put on a site called “hackaday”.

    Anyone have that list?

  17. Robert Spies says:

    Relays and other ‘electromagnetic’ things require some way to deal with the back-emf (‘flyback’) that results when the forward current is turned off.

    This is the reason for the diode when forward current is switched by a transistor.

    This is the reason for the capacitor in ‘points type’ automotive ignition systems. The capacitor delays (slows-down) the ‘flyback’, to give the ‘points’ time to open. Without the capacitor, the inductive energy will be dissipated at the points as ‘arcing’, not the spark-plug. The separate capacitor lowers the resonate frequency of the coil (and stray capacitance). [A low value resistor in series with the external capacitor is a good idea that will prevent momentary over-current as the coil is energized.]

    The higher the flyback voltage is allowed to go, the sooner the ‘flyback’ energy will dissipate. The volts X amps product (the flyback energy) is fixed (and equal to the forward energy used to ‘charge’ the inductor).

    External components can limit the flyback voltage (e.g., diode, Zener), or delay its voltage rise (e.g., capacitor), however will reduce the total energy.

    A single (Si) diode limits to 0.7 volts or so, and assures a relatively slow discharge of energy. Faster, is to let the reverse voltage go as high as possible (with due regard to the voltage rating of the switch, transistor, etc.).

    A capacitor will ‘slow-down’ the flyback and reduce its peak voltage, but will ‘absorb’ no energy, so the combination will ‘ring’ until the energy is dissipated in the resistance of the circuit.

    As regards relays for load control in systems such as you describe…

    Such systems require the ‘computer’ be on at all times the relay is to be energized. In addition, power to energize the relay must be available when needed. This seems less than optimal…

    Since controlling a light and many other loads, requires just one ‘bit’ of memory, why not use a relay that is a ‘one-bit’ (mechanical) memory in addition to its switching function?

    For this purpose I suggest either an ‘alternate-action’ or a ‘mechanically latching’ relay.

    Each time the single coil of an ‘alternate action’ relay is energized and released, the contact ‘state’ is changed.

    Each time a ‘latching’ relay, is energized and released, the contact ‘state’ will be determined by which coil was energized (of two).

    The more versatile of these relays will actually change their contact(s) position when the coil is de-energized.

    Such relays can be controlled by a computer pulse or by manual switches (of type SP3position, center-off). If an auxiliary SPDT contact set is provided, the relay can be energized to a ‘guaranteed’ turn-on (if it is off), and vice-versa, with such a switch. Since this is ‘normally open control’, as many switches (and computers) as needed can be wired in parallel.

    A person can determine if the relay needs to be ‘toggled’ by observing the load. A computer cannot do this without aid, so some means is needed to permit the computer to sense the ‘state’ of the load. Simplest is to use ‘auxiliary contacts’. ‘Auxiliary contact’ are less than optimal because they report the relay ‘command’, not what the load is actually doing.

    Better is to sense both the voltage across, and the current through, the load. With this information the computer can actually ‘know’ what the loaf is doing.

    When using ‘alternate action’ or ‘latching’ relays, the computer and/or power source can be shut-down (or fail) without affecting the ‘state’ of the relay (and load). In addition, manual control of the relay is possible with or without the ‘consciousness’ of the computer, however a power source to ‘pulse’ the relay is needed.

    If a means of controlling the load when no relay energization power is available is a requirement, a SPDT relay power contact can be used with a manual SPDT switch (this is the usual ‘two-way’ light switch hookup in residential wiring).

    If a second manual control switch is needed, a DPDT switch wired as a ‘reversing switch’ is needed. As many of these ‘reversing switches’ can be added as needed. This is the usual ‘three-way’ (or more than three ways) light switch hookup in residential wiring.)

    The load voltage and current sense (if provided) should always measure what is actually seen by the load, particularly when the load can be controlled separately from the computer.

    Relays provide one other feature than makes them particularly suited to many applications, This is the ‘galvanic isolation’ between the coil and each ‘set’ of contacts.

    AC and DC current sensing with ‘galvanic isolation’ is easily provided by using magnetics and the Hall-effect.

    Voltage sensing with galvanic isolation is more difficult, but routinely done in industrial controls.

    AC Voltage sensing can be done with a small ‘potential’ transformer.

    DC voltage sensing can also be done with a transformer — if the DC voltage is ‘converted’ to AC by use of ‘switches’ (actually transistors). The transistors are ‘driven’ with second transformer. If MOS transistors are used, the AC voltage output can be ‘synchronously rectified’, and will accurately ‘track’ the input DC-voltage over a wide range. (Due regard must be paid to the ‘switching time’ of the transistors and transformer!)

    (Long comment — sorry)

  18. @strider_mt2k I’ll make sure you’re the first to know if we ever publish a roundup of resistor calculators.

  19. therian says:

    what the point of 10K resistor, for a voltage divider it too small cutting only half volt from total, just to tie output pin to ground ?

  20. error404 says:

    @therian

    The 1K resistor is a current limiter to keep the base current low. The 10K is a pull-down to make sure the relay turns off if the input is left to float. Makes more sense to put the 10K ahead of the base resistor, but it’ll make little difference in this case.

  21. Roly says:

    At first glance this item seems trivial, and I wouldn’t bother to comment except that a number of statements are misleading, wrong, or significantly incomplete.

    “Inside the relay are two paddles made of metal. One paddle is made of a ferrous material like steel and is free to move. The other paddle is made of copper and stationary.”

    The moving “paddle” is actually called the armature (as it is in motors) and carries the moving relay contacts.

    These contacts can be made of many different materials depending on the intended service of the relay – plain copper, silver, gold flashed, silver-cadmium-oxide (“Silcadox”), mercury wetted, etc. Using the wrong contact material can result in very short contact life (e.g. gold flashed on high current), or failure to conduct when closed (e.g. Silcadox power relays on low voltage).

    The relay stator, or bobbin core, is also a ferrous material, *not* copper. There are relays that are intended for AC coil operation and these have a split pole which has a copper “shading” ring around one of the split poles (producing a phase lag and thus a net magnetic attraction).

    “The paddles are capable of carrying very large currents. Both AC or DC – the paddles don’t care.”

    They do actually. Relay contacts typically have two ratings, AC and DC, and the DC rating is typically only one-fifth to one-tenth of the AC rating. As mentioned above, contacts switching DC often need additional treatment to reduce contact arcing and resulting damage.

    “If you need 10A@120VAC, don’t use a relay rated for 10A@120VAC, instead use a bigger one …”

    A relay rated for 10 amp AC operation will give its rated switching life (e.g. 100,000 operations) switching that current. A key point is that the current rating is for a purely *resistive* load and the contacts must be significantly de-rated for reactive (typically inductive) loads.

    Don’t forget that lamp loads may be resistive but they also suffer from cold inrush currents from five to twenty times rated current that may cause relay contacts to weld and stick.

    Note also that solid-state relays and triacs are also prone to “stick on” when used with reactive loads and may require load-side power-factor correction to operate correctly.

    “The 1N4148 diode is connected in a odd fashion for a reason. This is placed between power and ground in a reverse fashion.”

    Actually it is placed across the relay *coil*, and should be as close as possible to the relay to avoid EMI to surrounding circuits.

    “the 1N4148 will forward bias causing the current stored in the coil to flow happily back to the 5V rail protecting the power supply and the near-by parts.”

    Now things start to get tricky. The object of this “catch” diode is to prevent damage to the driving transistor by shorting the coil back-emf. While just about any diode will serve this function there is a gotcha in that all diodes have a turn on time, and during this time the voltage may still spike to several kilovolts.

    This won’t kill the transistor because the duration is very short and may require a 100+MHz CRO to see, but it can still cause connected logic systems to malfunction/crash. The classic is the 555+relay that won’t time out, being retriggered by this spike. Adding a snubber of say 0.1uF in series with 47 ohms across the relay coil and diode will fix it.

    It should also be noted that anything that suppresses this spike will also extend the relay release time by a factor of ten or more.

    “Note: A two-wire extension cord will not work correctly. Notice we are using thick, three-wire circular extension cord. This extra wire is the ground return and allows the GFCI to operate correctly.”

    This is a typical misunderstanding of how an earth leakage breaker (GFCI aka ELB/core-balance relay/Safety Switch) works – an earth is *not* required on the load side, but is *vital* on the supply side.

    Note well that if you happen to be insulated from local earth by your shoes, stool, or mat, and happen to touch both active and neutral an earth leakage breaker *will not* save you – you are just part of the load.

    An earth leakage breaker is your *last* line of defence, not your first – *always* *unplug* before tinkering lest you log out forever.

    “The goal here is to ‘tin’ the three wires.”

    Wires intended for clamp connection should *not* be tinned as solder cold-flows under pressure and reduces the clamped pressure over time, worse with thermal cycling. Lead/tin solder also causes copper to embrittle, leading to fracturing where the tinning ends – significant where the assembly is subject to vibration.

    “Removing CTRL from the 5V rail (called floating because the CTRL line is neither connected to 5V or GND), …”

    This is emphatically not “floating” as the control signal is referenced to the relay coil supply. To be truly floating something like an opto-isolator is required.

    Relays may be old hat but they are still perfectly valid components in the right application, and like any component they require some understanding of their characteristics to avoid problems.

  22. Steve says:

    For those hackers that have to control lights, motors or other 120vac devices, there is a safe alternative (powerswitchtail.com) to doing your own wiring. This device inserts between the outlet and the load using standard 3-prong electrical hardware. The relay is actuated by a 5 volt dc control voltage that is isolated from the AC line.

  23. I used a simple relay connected to a parallel port and basic device driver to have my old 386 turn on my coffeemaker. Sure, I could’ve bought one with a timer, but where’s the fun in that…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 93,903 other followers