Ok. You are using an optocoupler to detect the mains presence. Am I right ? If yes, then you interface 50 Hz to MCU using optocoupler. You use INTx pin (external interrupt) to detect the presence of 50Hz signal. You should also use a timer interrupt. When ever a pulse is detected that comes from optocoupler then reload the timer registers. Say you have a timer of 100 ms. Also use a counter in timer ISR code. make sure whenever there is external interrupt you also clear this counter. So timer is reloaded every 20 ms and counter is cleared every 20 ms.