Electronic – Using 240v mains on/off as input to microcontroller


I have a light switch that switches 240v (UK) mains. Instead of using that to directly control a light, I want to use it as an input to a controller board so I can also automate the lighting. (It's low voltage LED lighting driven via a transformer although that doesn't really affect my question).

My question is what is the best and safe way to use switched 240v mains power as an input to a low voltage microcontroller circuit? It would be best to use the existing switch to switch a low voltage control signal but I can't change the wiring at at this time so the only input I have to my control is a switched 240v mains power line.

I have other power available where the controller is so I'm not intending to power this via the original light power, I just want to see if I can use it as a control line without extensive rewiring work for now.

Best Answer

I have been using this circuit for a long time now:

220V to uC

300 K resistor on high side limits the current to a safe level. Make sure it satisfies the voltage ratings. As pointed out by @Jeroen3, a 0805 resistor wont be enough for the job.

Optocoupler is K814P. Usually 817 series is single direction and 814 is dual direction. Ex - PC817 and PC814.

RC network on output side smoothens the ac output and maintains a contant DC voltage on output pin which can be fed into any microcontroller.

When you close the switch, you will get an instant HIGH on OUTPUT pin but when you open the switch, it will take a while (300 ms or so) for the OUTPUT pin to go LOW due to the 0.1 uF capacitor. If you want to decrease this time duration, play around with the values of R and C. Reducing them will give you a faster response.