Hi,
Timer overflow interrupt routine is called when main 16-bit free-running timer (TCNT) overflows from 0xFFFF to 0x0000.
For example: rising_edge = 0xF000; overflow = 3; falling_edge = 0x2000; then:
number_of_cycles = (0xFFFF * (unsigned long int)overflow) + falling_edge - rising_edge
number_of_cycles = (0xFFFF * 3) + 0x2000 - 0xF000 = 0x22FFD;
Back to your first question: Can we use PIT for such detection?
Idea 1: IC timer function (previous proposal)
Idea 2: We can connect signal from proximity sensor to port with pin interrupt (Ports P, H, and J). In interrupt routine we can start some output compare function for measuring 2s and set some flag. Timer interrupt will signalize 2s quiet on line and we should clear our flag. When pin interrupt occurs before 2s time interval (our flag is still set) finishes, we should reset OC timer for measuring 2s again. Note: pin interrupt could be set to rising or falling edge, unfortunately not simultaneously. Detected edge could be set by PPSP (PPSH, PPSJ) register.
Disadvantage: PIT is not suited for such general OC function (periodic interrupt) and 2s could be too long interval for ECT (we should work with overflow …).
Idea 3: We can connect signal from proximity sensor to port with pin interrupt as in case 2. We can configure PIT for generating interrupt with period for example 100ms. In PIT interrupt routine we will increment counter and when counter>=20 we should generate some action. In pin interrupt routine we will simply clear this counter (plus change polarity of detected edge).
Disadvantage: we measure 2s with maximum error = 100ms (periodic interruptionand edge detection are independent). So, question is how accuracy of this 2s interval you need.
Note: for this purpose you can use also RTI (real time interrupt).
I found some similar example code for this case (Idea 3). I hope that help you.