How to identify if a switch connected to mains is closed using arduino? - Page 1
Forum section: electronics / beginners

author: redgear
author_rank: Frequent Contributor
timestamp: July 24, 2020, 08:50:41 am
content: I would to like detect the state - ON or OFF of a SPST switch that is connected to the mains using a Arduino or any other microcontroller. The switch when closed connects to a relay's COM port. What's the most safest and reliable way to do it? I initially thought of using a current sensor but that would work because it detect only if any current flows in the circuit and does not work when the switch is ON but no current flows through it.Thanks

author: greenpossum
author_rank: Frequent Contributor
timestamp: July 24, 2020, 08:53:15 am
content: Optocoupler?Neon bulb and LDR?

author: redgear
author_rank: Frequent Contributor
timestamp: July 24, 2020, 09:11:51 am
content: Quote from: greenpossum on July 24, 2020, 08:53:15 amThanks.I am thinking to go with the optocoupler route. Looking for example circuits. Found few on stackexchange!

author: Ian.M
author_rank: Super Contributor
timestamp: July 24, 2020, 10:02:34 am
content: You need to consider the rest of the circuit to even know if the switch state is detectable. e.g. what's connected to the NO and NC terminals of the relay. If there's any other path for mains to get back to the COM terminal, detecting the switch state is non-trivial.At its simplest you might use a sensitive AC input optocoupler with a 120K dropper resistor feeding it, for 1mA RMS through its LED pair. If you need more drive, it gets nasty as the dissipation in a resistive dropper goes up steeply, so for approx 10mA drive, I'd suggest a 220nF capacitive dropper (with a 2K7 1/2W series anti-surge resistor).If you want us to critique the circuits you have found, post links.

author: redgear
author_rank: Frequent Contributor
timestamp: July 24, 2020, 10:34:26 am
content: Quote from: Ian.M on July 24, 2020, 10:02:34 amNC is not connected. NO is connected to a lamp. The relays are protected using a S1M diode to prevent voltage spikes. I just need to detect if the switch is ON. I can wire the mains output from switch directly to the COM and the optocoupler. I want to be able to turn this relay and another one ON when the AC switch is closed using a microcontroller.QuoteThanks. Yes, that would be great.It's 150nF cap, not 150uF.Can I use a logic output optocoupler that I can directly hook up to a microcontroller, instead of a using a LED or something?My aim is to just know if the Switch is open or closed.

author: NivagSwerdna
author_rank: Super Contributor
timestamp: July 24, 2020, 11:01:59 am
content: https://m.eet.com/media/1133289/6512151.pdfandhttps://hackaday.io/project/26352-detecting-mains-voltagecurrent/detailsmake interesting reading

author: redgear
author_rank: Frequent Contributor
timestamp: July 24, 2020, 11:16:48 am
content: Quote from: NivagSwerdna on July 24, 2020, 11:01:59 amThanks. I think this circuit will suit my requirements. I guess I can read the OUT using the arduino digital pins.

author: ledtester
author_rank: Super Contributor
timestamp: July 24, 2020, 11:42:56 am
content: Quote from: redgear on July 24, 2020, 11:16:48 amWith the internal pull-up resistor on the GPIO pin enabled, of course.May I ask what the application is? Why do you have to use an AC switch? Why not use another more Arduino friendly switch?

author: redgear
author_rank: Frequent Contributor
timestamp: July 24, 2020, 01:09:16 pm
content: Quote from: ledtester on July 24, 2020, 11:42:56 amThanks. This kind of a safety switch. Designing it in such a way that the power to the load is cut-off as soon as the switch is released. This switch power a relay which then connects to the load. I want to detect the state of the switch just so I can program the uC to power the relay ON only if the switch is closed.

author: vk6zgo
author_rank: Super Contributor
timestamp: July 24, 2020, 02:07:43 pm
content: As I have an aversion to putting Mains anywhere near a microcontroller, I would suggest the following.(1)Buy a very small Mains to 6v, 12v, or whatever, transformer, rectify the secondary voltage & detect the DC.Or:(2)Use an ac operated relay to switch the input state of the Arduino.If you are already using relays for other jobs, you should have enough room to fit another, so (2) would be the "quickest & dirtiest" way.

author: redgear
author_rank: Frequent Contributor
timestamp: July 24, 2020, 02:21:49 pm
content: Quote from: vk6zgo on July 24, 2020, 02:07:43 pmThanks for the idea. Let me try this

author: calzap
author_rank: Frequent Contributor
timestamp: July 24, 2020, 02:40:53 pm
content: Can the SPST switch be replaced with a DPDT switch? Other pole of the DPDT could be used to signal the Arduino, which can be programmed to detect whether a pair of contacts is opened or closed. For the pole going to Arduino, you should give careful consideration on whether to use the NC or NO position ... the Arduino can be programmed either way. You'd want to use the position that provides the greatest safety in case of failure.Mike in California

author: Ian.M
author_rank: Super Contributor
timestamp: July 24, 2020, 02:54:04 pm
content: I really wouldn't risk running mains and low voltage through adjacent poles of a multi-pole switch, unless its rated for safety isolation between poles.As I said earlier a simple 120K resistor and an AC input optocoupler will do the job. For 115V mains, the resistor needs to be 1/4W and have a 200V voltage rating. If you want a bit more safety margin to handle mains spikes use two 62K resistors in series. In 230V countries use two 120K or three 82K resistors in series. Somewhat lower resistor values may be chosen at the expense of power dissipation if you need a bit more drive.If you cant easily source an AC input optocoupler, get a dual optocoupler, and wire its input side LEDs anti-parallel (i.e. link each anode to the other's cathode) and its output transistors in parallel.Assuming a 5V MCU with weak pullups equivalent to 20K resistors, as long as the min. CTRR is 20% or greater, the optocoupler will output a valid logic '0' level for 30% or more of the mains cycle, going high near the zero crossings or if no mains is present. If you need it low for a greater proportion of the cycle, choose an opto with a greater min. CTRR (including allowance for ageing), use a higher value external pullup, or use lower value input side dropper resistors (but recalculate their power dissipation).Its critical for safety that you maintain the maximum possible clearance between the mains and low voltage sides of the optocoupler. Don't use matrix-board or stripboard. If you must use protoboard then use plain (no copper) perfboard and point-to-point wiring techniques. On a PCB, don't run *ANY* tracks under the optocoupler.

author: KMoffett
author_rank: Regular Contributor
timestamp: July 24, 2020, 03:07:15 pm
content: Simple isolated detector. Yes, there is a current to the load with the switch open, but the current limiting resistor in the neon module limits to a safe level.

author: calzap
author_rank: Frequent Contributor
timestamp: July 24, 2020, 03:18:52 pm
content: I think any multi-pole, agency-approved (UL, CSA, TUV, etc) for mains switch would have sufficient isolation between poles. Most practical means of detection will bring the mains and signal circuits close in space at some point. Some exceptions would be a sensitive inductive circuit or a lamp on the mains with a photo-detector some distance away. For safety, the means of detection should be in the same enclosure as the mains switch.Mike in California

author: Ian.M
author_rank: Super Contributor
timestamp: July 24, 2020, 03:31:00 pm
content: I've seen mains DPST rocker switches that after some time barely had functional insulation between the poles. They may have been OK when brand new, but by the time repeatedly switching an inductive load had sputtered some of the contacts as a thin film over the interior of each contact enclosure, the creepage distance was definitely compromised.@KMoffett,You are over-complicating it. Put the neon indicator across the load, and as LDRs are typically rather slow at low light levels, odds are you can omit the diode and everything to the right of it, and can go straight to an ADC input.

author: calzap
author_rank: Frequent Contributor
timestamp: July 24, 2020, 04:12:13 pm
content: Ian,Guess we won't agree. For decades, I've used 2-pole Leviton commercial and industrial grade toggle switches at a minimum of 50% of rated amps at 240 VAC without an issue. I know there are crummy switches out there; some with agency approval on them. And these days, fake brands and agency approvals abound. Can't get simpler than a DP switch.I think though we should know more details about the OP's application. Is the switch part of building wiring? If so, there may be code issues and an inspection requirement.Mike in California

author: Ian.M
author_rank: Super Contributor
timestamp: July 24, 2020, 07:39:32 pm
content: I think we are probably closer to agreement than you think. e.g. I suspect that finding industrial grade switches with adequate pole to pole isolation wouldn't be particularly difficult. Heck, I've seen some with a panel mount actuator assembly and demountable contact sets, each pole of which was a standard microswitch.

author: vk6zgo
author_rank: Super Contributor
timestamp: July 25, 2020, 12:44:28 am
content: Back in the day, switches, contactors & circuit breakers with a separate mechanical actuator to operate a microswich were commonly used in power circuitry of large Broadcast Radio transmitters, so at least in the past, such devices were standard components.There are many ways to do what the OP requires, but some of them are less intrusive to an existing system than others.

author: calzap
author_rank: Frequent Contributor
timestamp: July 25, 2020, 02:47:20 am
content: Even today, many contactors come with "auxiliary contacts" or it's an option to stick such contacts on the side. Auxiliary contacts have a much lower current rating than the main contacts.Mike in California

author: ledtester
author_rank: Super Contributor
timestamp: July 25, 2020, 04:46:00 am
content: Quote from: redgear on July 24, 2020, 01:09:16 pmJust want to double check this... you want current to flow through the relay coil only if a) the switch is closed and b) the Arduino allows power to the relay coil?

author: redgear
author_rank: Frequent Contributor
timestamp: July 26, 2020, 10:20:33 am
content: Quote from: calzap on July 24, 2020, 02:40:53 pmNope, I cannot use a DPST.Quote from: Ian.M on July 24, 2020, 02:54:04 pmThank you for the suggestions. I will try implementing this.Quote from: KMoffett on July 24, 2020, 03:07:15 pmThank you!Quote from: ledtester on July 25, 2020, 04:46:00 amYes, you are correct.

author: ledtester
author_rank: Super Contributor
timestamp: July 26, 2020, 11:53:08 am
content: Quote from: redgear on July 26, 2020, 10:20:33 amSo how about this...Instead of an Arduino GPIO pin driving the relay coil, it's driven by the output of an AND gate. The inputs of the AND gate are the Arduino GPIO pin and the switch which is now a low voltage switch.Then have the high-voltage side of the relay turn the load on and off.The relay coil will not be energized unless both the Arduino and the switch want it to be energized. It is not exactly the same as having the Arduino knowing if the switch is closed, but the AND gate still protects you against software programming errors, and you won't be wasting low-voltage power energizing the relay if the switch is off.Update: Just realized that now that the switch is now a low-voltage digital signal, you could detect it with another Arduino GPIO pin as well as have it connected to the AND gate.

author: Ian.M
author_rank: Super Contributor
timestamp: July 26, 2020, 12:15:01 pm
content: OTOH if the switch is really necessary for safety, you'd want to keep it directly interrupting the mains supply. Even if you move it to interrupt high side feed to the relay coil, where you could easily monitor its state, but the risk of any fault in the control circuit rendering it ineffective is minimal, its still compromised by the risk of the relay contacts welding closed.Another issue is that a switch that has been used for switching AC mains is unlikely to be reliable for low current logic level switching due to pre-existing contact burn, and further deterioration of the contact surfaces due to oxidisation and contamination from outgassing without sufficent wetting voltage or current to clear it.

author: redgear
author_rank: Frequent Contributor
timestamp: July 26, 2020, 01:12:40 pm
content: Quote from: ledtester on July 26, 2020, 11:53:08 amThat's how I have it now. I want to directly cut-off the mains supply as it is a fail-safe alternative. Its guaranteed to cut-off even if the relays coils are iced.Quote from: Ian.M on July 26, 2020, 12:15:01 pmYep, that's exactly what I am trying to do. The hackaday link someone posted is used for something very similar. I think I can go with that.Hereis the circuit. Let me know your thoughts.

author: Doctorandus_P
author_rank: Super Contributor
timestamp: July 27, 2020, 08:41:28 pm
content: Connect the "GND" of your arduino to "earth".Connect some other end of the arduino to the switch with thick wire.If nothing happens, the switch is open.If the arduino smokes, the switch is closed.Simple.

author: ledtester
author_rank: Super Contributor
timestamp: July 27, 2020, 11:23:04 pm
content: Quote from: redgear on July 26, 2020, 01:12:40 pmI need to see a complete schematic including the switch, load and relay.If everything is in series you won't be able to query the detector without energizing the relay. Also, those 270K resistors are going to impede current through the load. Or am I missing something?

author: Ian.M
author_rank: Super Contributor
timestamp: July 28, 2020, 01:46:25 am
content: Sarcasm much? I *ASS*U*ME* you know better than to put the input side of a low power high impedance mains voltage detector circuit like the Hackaday one linked in Redgear's reply #24 in series with the relay contacts and load. It obviously goes between the point being monitored (after the switch) andgroundNeutral.@Redgear,The Hackaday circuit isn't bad for getting adequate optocoupler LED drive without excessive power consumption, but it throws away all the benefit of robust pulsed drive by the moronic output filtering, which makes it incapable of pulling low against even a 10K pullup, and also makes it very slow to respond to loss of mains.IMHO you should delete the 10uF output capacitor, and connect it to an interrupt pin with a pullup. If its 'seen' a pulse within the last 22ms, (1 cycle +10%), the input side's got mains applied. If you aren't using a MCU, use a retriggerable monostable with the above period.LTspice sim attached - ZC3 is the Hackaday version. ZC4 adds my tweaks to the input side, for more drive to the opto LED (might as well run it at the peak of its CTRR vs If curve), to improve its accuracy in zero crossing timing applications, and to prevent its self-destruction if rectified mains or other HV DC is ever applied to its input.N.B. the 4N37 is a high CTRR optocoupler, with min. CTRR of 200 @ 2mA If. Most non-darlington optocouplers have much lower CTRRs and will have vastly inferior performance in this circuit. see 4Nxx datasheet:http://www.ct-micro.com/uploads_zip/4N25.pdf

author: ledtester
author_rank: Super Contributor
timestamp: July 28, 2020, 02:32:24 am
content: I didn't mean any sarcasm - I'm just trying to figure out how things would actually work.So would the detector be in parallel with the relay?Code:DETECT/ \LIVE --- LOAD --- SWITCH --- --- NEUTRAL\ /RELAY

author: Ian.M
author_rank: Super Contributor
timestamp: July 28, 2020, 03:03:04 am
content: More like:Code:LINE -----o-------------------------|\ o\\. Switcho|o-----------------.| || |\ o |\ |\. Relay Contacts |o .----o----.| | Opto || | Voltage || | Detector|.-. | || | '----o----'| |Load |'-' || || |NEUTRAL -o-----------------'---------(created by AACircuit v1.28.6 beta 04/19/05 [url=http://www.tech-chat.de]www.tech-chat.de)

author: redgear
author_rank: Frequent Contributor
timestamp: July 28, 2020, 04:37:15 am
content: Quote from: Ian.M on July 28, 2020, 01:46:25 amThank you very much for the spice simulations and suggestions!Edit: Can the 1N4148 be replaced with a S1M diode? And the 330nF cap on the input side should be a AC rated cap, what type should it be? will a X7R be fine? How much ripple current should it be rated for?QuoteYour ZC4 has a 10uF cap on the output, do you suggest removing it and connecting output directly to the interrupt pin or a retriggerable monostable?

author: Ian.M
author_rank: Super Contributor
timestamp: July 28, 2020, 07:18:27 am
content: The 1N4148 can be replaced by *any* small signal silicon diode.The input side capacitor doesn't need an AC rating - the Zener keeps the voltage across it low and prevents it going significantly negative. It also has negligible ripple current - a mARMSat most(due to the low duty cycle of its pulse discharge). Any 25V rated ceramic of the desired value will do, or 16V if its a filmcap or not a high-K ceramic.Yes, remove the 10uF cap on the output side. I've prepared another sim, ( Put it in the same folder as the previous sim - it needs the 4N37 optocoupler model.) which I've further tweaked to minimise the falling zero crossing to falling Int output pulse delay. It also shows how you *could* get a logic level active low 'mains present' output, if you aren't using a MCU. It uses aLTC6994-1TimerBlox delay chip (not the cheapest way to implement the output pulse stretching, but LTspice doesn't have many simple monostables).If you are using a MCU, you don't need the TimerBlox chip, as you can simply drive an Int pin from the optocoupler output. It stays low for approx 1ms so even the most snail-like MCU would have time to respond. You also need a 'tick' interrupt to increment a counter (limiting so no wraparound). The Int pin ISR clears the counter. If it ever goes over a count equivalent to 24ms, mains in is not present.Edit: clarify ripple current

author: redgear
author_rank: Frequent Contributor
timestamp: July 28, 2020, 08:44:52 am
content: Quote from: Ian.M on July 28, 2020, 07:18:27 amThank you once again.I will check it out and update this thread with the schematic.One more question, how reliable are optocoupler circuits? After doing some reading on the internet, many blog posts claim them to have a low reliability, is that something that I should be concerned about?

author: Ian.M
author_rank: Super Contributor
timestamp: July 28, 2020, 09:38:19 am
content: Optocouplers are extremely reliable - *IF* you design the circuit they are in properly.Its essential to respect their maximum ratings, and always have an adequate safety margin. e.g. consider the 4Nxx series datasheet I linked from reply #27. The Absolute Maximum Ratings are on page 2, and I would design to a maximum limit of no more than 80% of the ratings on that page, as the closer you push the limits the lower the reliability. If economics permit and reliability is a priority, derating to 60% is a better choice. Of course, you also need to be using the right datasheet, preferably from the actual manufacturer of your specific parts!Also, the opto LED's light output *WILL* drop with age, so its prudent to make sure your design has at least twice as much output drive capability as it actually needs. You can usually get more output drive by increasing the input side LED current, but if you are on the far side of the 'hump' in the CTRR vs If curve (see fig. 5 in that datasheet) there are diminishing returns. Consider a 4N35 for simplicity. Its min. CTRR is 100%. looking at fig. 5, if you want to run it at only 1mA If, that drops to 40%. That means the phototransistor wont be able to reliably pass more than 0.4mA. Its worse if you need to operate at high temperatures - fig.7 tells you the CTRR could drop al low as 20%. That particular datasheet has no reliability or life expectancy data, but its fair to assume its good for 10000 operating hours. However, running 24/7 that's under 14 months. If you want top push that out to a reasonable lifespan you need that extra factor of two CTRR margin I mentioned earlier. If you were sticking to using a 4N35 at 1mA If, and high temperature, you could therefore only count on 0.1mA Ic after several years of operation.I would suspect that most of the people complaining about unreliability started with a circuit that worked on the bench as a prototype, and failed to allow for device to device CTRR variation, other component tolerances and aging so their final build failed prematurely. Its worse if you fail to derate when designing for production - if you don't have adequate margins, its easy to get into the situation where a significant percentage are faulty right off the production line and anywhere from 50% to 90% of the 'good' ones fail within a year. You can also get that level of screwup by improper handling on the production line e.g. storage inappropriate for their moisture sensitivity level, no ESD precautions in a low humidity environment, or using a bad reflow profile, (see page 13 of the 4Nxx datasheet)Failure to design conservatively by appropriate derating is failure as an engineer and is likely to put your job on the line.

author: redgear
author_rank: Frequent Contributor
timestamp: July 28, 2020, 10:33:19 am
content: Quote from: Ian.M on July 28, 2020, 09:38:19 amUnderstood, thank you for the detailed explanation.The two 270k resistors should have a voltage rating of twice the mains and a power rating of 1/4 W, am I correct?How do I determine the power ratings for resistors R1, R4 and R3?

author: Ian.M
author_rank: Super Contributor
timestamp: July 28, 2020, 11:59:21 am
content: The Hackaday derived circuits I have posted are for 240V 50Hz operation. For other supply voltages and frequencies, R2 will need changing:115V, 60Hz use 2x 120K, 1/4W230V, 60Hz preferably*use 3x 180K, 1/4WThe worst case dissipation per R2 resistor is *far* lower than 1/4W, but specifying 1/4W through-hole will almost invariably lead to a resistor with adequate voltage rating and a length that provides an adequate creepage distance. For a surface mount build, you'd need to check the resistors actual voltage ratings, and consider slotting the PCB under each R2 resistor.The other resistors all have negligible dissipation - you can either prove that from V2/R, or I2R, and the worst case peak voltage or current in a back-of-the-envelope calculation, and you wont even need to go as far as considering duty cycle, or, as you've got the LTPICE sim, you can set the mains and 5V supplies to worst case 10% high and alt-click the part you want to plot the dissipation of.* 2x 200V resistors in series is extremely marginal as a 230V RMS mains supply dropper resistor. During high line conditions the peak voltage can reach 360V, leaving negligible headroom for transients.

author: redgear
author_rank: Frequent Contributor
timestamp: July 28, 2020, 12:11:00 pm
content: Quote from: Ian.M on July 28, 2020, 11:59:21 amThanks! I will post a schematic soon for review.