PIC16F819 count down timer

I’m a newbie to this site, so please excuse me if I’m posting in the wrong forum section, or if my question is too elementary. I’ve just recently started using MPLab with a CCS complier to program a PIC16F819 I’m trying to write a code in which a single LED is switched on if 2 certain switches are pressed within 2 seconds of each other. I’ve started a basic code in which I have 4 inputs (switches) and four outputs (LED’s) at the moment each switch corresponds to a single LED so if I was to press switch1 then LED1 lights up.

I want to program the PIC so that LED1 would light up if I was to press switch1 and then switch2 (within 2 seconds of each other). I was thinking of using a 2 second count down timer and then using an “if” statement so that if the timer hasn’t reached zero and the second switch is pressed then the LED lights up. However, I have no idea how to program a count down timer can someone please help me with the coding required.

Thanks in advance.

Current code:

#include <16F819.h>

#fuses INTRC_IO,NOWDT,NOPROTECT,MCLR,NOBROWNOUT

#use delay(clock=4000000)

#define SW2 PIN_B7

#define SW2 PIN_B6

#define SW3 PIN_B5

#define SW4 PIN_B4

#define LED1 PIN_B3

#define LED2 PIN_B2

#define LED3 PIN_B1

#define LED4 PIN_B0

void main()

{

port_b_pullups(TRUE);

while(1)

{

if(!input(SW1)) output_high(LED1);

if(!input(SW2)) output_high(LED2);

if(!input(SW3)) output_high(LED3);

if(!input(SW4)) output_high(LED4);

}

}

Are you familiar with interrupts? One of the easiest ways to implement what you are trying to do is to have a timer running in the background generating interrupts at regular intervals. Every time it interrupts, you increment a variable that keeps track of your “time.” When your first button is pressed, you make a copy of the current time. When the second button is pressed, you take another copy of the current time. You can then subtract the first time from the second time to see the difference between them. If that difference is 2 seconds or less, you would then light up the appropriate LED.

Timer2 in the PIC is well suited for setting up these types of interrupts since it includes a period register, prescaler, and postscaler, all of which allow to effectively divide your clocks by an arbitrary number to get the scaling you need. Page 63 of the datasheet has a diagram of Timer2 so you can see the parts I’m talking about.

If you want a 10ms update rate (100Hz), you can take the 2MHz input and divide it by 16 in the prescaler for a new clock speed of 125Khz. To get a 100Hz output, you need to divide 125,000 by 1,250. Because PR2 is an 8-bit register, 1,250 will not fit into it so we can use the postscaler in divide by 10 mode which allows us to load PR2 with 125.

I’m not familiar with the CCS compiler so you will have to work out how to get your system configured in this manner.

-Bill