There are dozens of ways to do this, but in this case, I'm referring to the circuit that I described earlier - an optoisolator. The input pin in my code would be connected to the collector of the phototransistor in the optocoupler. If you build the circuit I described, you will find that the output of the opto is a square wave, with a period equal to the period of your AC (60 Hz = 16.666 ms, 50Hz = 20 ms). The output will be low for one half-cycle (8.3ms or 10 ms) and high for the other half-cycle. The low-to-high and high-to-low transitions will occur on the zero-crossings of the AC. The circuit only detects "positive" half-cycles.
The counter increments every 5 msec, but if a half cycle comes along, the counter gets cleared (because the pin is low), and the count never gets above 2. If a positive half-cycle is missing, the counter increments to 3 and you get an indication that your power is gone.
PULSIN and COUNT are sometimes called "blocking" commands because between the invocation of the command and the timeout, the code can do nothing else. I generally avoid them at all costs.
Bookmarks