Using 240v mains on/off as input to microcontroller
I have been using this circuit for a long time now:



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.