The external hardware and internal clamping diodes will make a square wave signal on the AVR’s External Interrupt 0-pin. As described in the hardware section the square wave will have the same frequency as the AC mains. The high period of the signal will be when the AC mains amplitude is above VCC/2. This gives mains zero crossings very close to the edges of the square wave. The rising edge of the square wave is slightly after the crossing, and the falling edge is slightly before the crossing.

As the falling edge of the square wave is just before a zero crossing, the falling edge interrupt will occur so close to the actual crossing that it immediately can start the zero crossing action.

In this application example the zero crossing action will only be to set PB0 high for a short period of time and then immediately start looking for the next falling edge zero crossing. This makes it very easy to check if the zero crossing detection is correct or not. Simply connect an oscilloscope probe to the mains and another to PB0. If the detection is correct this will show PB0 going high for a short period of time at each negative edge zero crossing (see the first two figures below).

Figure 1. Screen-shot from Oscilloscope, Mains Input and PB0 Output
Figure 2. Screen-shot from Oscilloscope, Mains Input and PB0 Output

In a real application the disabling of external interrupt 0 before returning from the interrupt routine will make a single detection. To detect a new zero crossing, simply enable the falling edge interrupt again in the main program.

To make sure the interrupts are valid and not only products of spikes on the pin, there is a filter implemented in the interrupt routine. The filter samples the level on the interrupt line five times and compares the values to see if the value is stable. If the value is not the same for all the samples, the event is discarded and the routine returns to the main program waiting for a new interrupt (see the figure below).

For more details about the software, see the comments in the code.

Figure 3. Software Flowchart for Main Program and External Interrupt 0 Handling Routine