Zero-crossing detection
There is no need for tricky software.







simulate this circuit &ndash; Schematic created using CircuitLab

Figure 1. Replacing D2 with a bridge rectifier will turn on the opto-isolator on both positive and negative mains half-cycles.

Your 59k value for the current limiting resistor, R5, seems suspiciously low. You should check your calculations for this and the power rating. Most carbon or metal-film resistors are only rated for 200 V or so. Your 220 V mains will peak at \$ 220 \sqrt 2 \ \text V \$ so it is usual to use two series resistors to make up the required value.









simulate this circuit

Figure 2. A second 4N35 could be piggy-backed onto the existing one. Note that the LED terminals require a cross-over.