False triggering in mains button detection circuit with optocoupler - Page 1
Forum section: electronics / beginners

author: coolkitty
author_rank: Newbie
timestamp: July 06, 2025, 08:07:34 pm
content: I am working on an AC mains sensing circuit involving aPC817Coptocoupler to detect a momentary button press.The circuit details are as follows:- button connected in series with a 100mA fuse and two 100kΩ resistors on the live wire (230V 50Hz AC);- 1N4007 diode antiparallel with the optocoupler LED for reverse voltage protection;- optocoupler’s transistor output pulled up to 3.3V through a 6.8 kΩ resistor and connected to the RP2040-zero microcontroller's GPIO12.The problem I faced during testing is that when a fan or light is switched on or off from a socket close by, the microcontroller often falsely detects a button press, despite no actual press occurring.Given that this circuit will be used for home lighting it should be as stable and safe as possible.I have a small handheld oscilloscope, but I wasn't able to catch any visible glitches with it.When the button is pressed I've measured 1.2mA on the AC side, while on the low side the square wave averages to 0.2mA.Simplified code and schematic are attached, simulation ishere.Thank you in advance for any insights!

author: PGPG
author_rank: Frequent Contributor
timestamp: July 06, 2025, 09:19:21 pm
content: It would be good to know at what PC817 side the disturbance is received. It can depend of wire lengths and we know nothing about it in your circuit.To find it short PC817 pin1 with pin2 and check if problem still exists.Whatever you will find I suppose the disturbance pulse is much shorter than pulse you get when button is pressed.What is the output pulse length when button is pressed?If you need you can make it longer by using smaller resistors at input.You can filter out short pulses by adding RC filter between PC817 output and uC input or you can filter it out with software. When you see pulse check if it is still after some time and only then assume it is walid pulse.

author: Doctorandus_P
author_rank: Super Contributor
timestamp: July 07, 2025, 10:35:11 am
content: What sort of handheld scope do you have? Both the Owon and Hantek ones are quite decent, Fnirsi is utter garbage because that company lies in their specifications and can not be trusted. A gadget like the "DSO Shell" is a bit of a toy, but it's also about worth what you pay for it.Adding a filter is probably the simplest solution.Your PC817 only lights up on the "positive" half of the AC mains input. 3.3/6800 = 0.48mA, so that you're measuring a bit less then half of that sounds about right. For humans, a delay of 100ms is barely perceptible. You can dimension your filter that 4 or 5 mains pulses must be present before the signal is accepted as valid. This can be done with a bit of analog electronics, or it can be done just in software.Some words about safety:Here in the Netherlands, mains plugs are reversible. (And I think in Italy too). That means you can not rely on one wire being "mains" and the other being "neutral". I also don't know what sort of resistors you use. Some THT resistors can be rated for voltages as low as only 100V, so check what you have. For mains voltages, I tend to put 4 resistors in series, and then put two of them in "mains" and two in the "neutral" wire, so you still have some protection when the plug is reversed.

author: Circlotron
author_rank: Super Contributor
timestamp: July 07, 2025, 12:37:08 pm
content: You could put a 10nF AC rated capacitor between the Live and Neutral points on your circuit. This will soak up any short high frequency spikes that might be coupled by stray capacitance into your sense circuit.

author: Doctorandus_P
author_rank: Super Contributor
timestamp: July 07, 2025, 03:45:14 pm
content: Quote from: Circlotron on July 07, 2025, 12:37:08 pmI also thought of advising this. such capacitors are very common in SMPS circuits where an optocoupler is used in the feedback loop, but I decided against this, as I do not like creating any connection over the optocoupler if it's not needed, and in this case, there is no "high speed" feedback needed as in an SMPS. For low speed (100ms reaction time) it's easy to just filter on the secondary side of the optocoupler.A filter on the primary side is also an option. You can put a capacitor parallel to the 1N4007. This forms a low pass filter with the two 100k resistors. When you add a few more diodes in series with the LED in the optocoupler, you can also raise it's threshold a bit. But I don't know OP's experience level, and putting as much as possible on the secondary side of the optocoupler is better from a safety point of view.

author: coolkitty
author_rank: Newbie
timestamp: July 07, 2025, 05:05:20 pm
content: Thank you all for your inputs. The problem was solved with software.Quote from: PGPG on July 06, 2025, 09:19:21 pmQuote from: Doctorandus_P on July 07, 2025, 10:35:11 amI changed thebutton_IRQfunction to only count a pulse if it happens at the AC frequency of 50Hz. So, checking if every new falling edge is about 20ms from the previous one. This also got rid of contact bounce. (Therefore, a more appropriate name for what I calleddebounceMsin my original code should have beenpollingIntervalMs, but anyway)def button_IRQ(self, pin):now = time.ticks_ms()period = time.ticks_diff(now, self.lastEdgeTime)if abs(period - 20) < 3:self.squareWaveCounter += 1self.lastEdgeTime = nowand in the poll function:if time.ticks_diff(now, self.lastEdgeTime) > waveTimeout:if self.buttonPressed:if self.squareWaveCounter > 2:self.toggleAction = Trueself.buttonPressed = Falseelse:if not self.buttonPressed:self.buttonPressed = Trueself.squareWaveCounter = 0self.lastEdgeTime = nowFor the sake of completeness, I'll report my feedback from testing the hardware too:First I’ve tried disconnecting the AC side completely. To my surprise the disturbance was still there. After replacing the 15cm jumpers with shorter wires, the room’s light switch didn’t interfere anymore, but the fan sometimes still did.Next I tried changing the 5V supply of the circuit. PC, laptop, and wall adapter. No luck. I also added some capacitors to the power rails for good measure.Plugging the fan’s power cable in the other side of the room stopped the interference only if the fan was also kept far. Bringing it closer to the circuit caused false triggering again. Keeping it plugged in close by and moving the fan far away still caused interference.Adding a 1nF or 10nF safety capacitor on the AC side didn’t make any difference.Then I tried adding the RC filter to the microcontroller’s input. 330Ω and 1uF, which should give a cutoff frequency of ~480Hz. Each pulse now had a smooth sawtooth shape. This improved things a bit, but I was still able to get it to false trigger occasionally.It’s still crazy to me how sensitive the microcontroller’s input pin is. Just adding a floating jumper to the opto’s output makes it pick up so much noise.Quote from: Doctorandus_P on July 07, 2025, 10:35:11 amI’m now prototyping with standard THT resistors with unknown voltage rating, but the final device will have a custom PCB and 2010 resistors rated for 200V. Two resistors will see ~165V each at peak. I could consider doubling them as you suggest. Would that simply be four 51k resistors, two on the live and two on the neutral? Anyway, I will wire the circuit myself to the house buttons, so I’ll make sure live and neutral are connected correctly.Quote from: Doctorandus_P on July 07, 2025, 10:35:11 amI have the crappy Fnirsi DSO-TC3, when I bought it I just needed some cheap thing to at least see if signal was present, and for that it works ok. It’s better than having nothing, but now that I’m starting to venture into more complex projects, I see how limited it is. Currently saving to buy a good desktop oscilloscope.Quote from: Doctorandus_P on July 07, 2025, 03:45:14 pmThis is my first time working with mains voltage. I've done many projects with low voltage LEDs, PWM and digital signals in the past years, so the next part of this project should go more smoothly. This board will have two MOSFETs with gate drivers to PWM a variable temperature 24V LED strip. Ideally, I would like to reach a high enough frequency to avoid any flicker or stroboscopic effect while also having enough resolution for gamma compensation.I've also added a thermistor to detect excessive temperature within the enclosure. The design should be thermally fine, but GPIO pins are free and a thermistor is just a few cents.Without going too much off topic, are there any other safety measures I could implement?