/**
 * Interrupt Flasher.  The program sits there and does nothing while 
 * interrupts fire periodically and increment PORTA.  Like 
 * 0002-interrupt.c except this time we're using timer2.
 *
 * timer 2, like timer 0, is an 8-bit counter.  It ONLY counts from
 * the CPU clock, it has no external input.  Its prescaler is entirely
 * seperate and a bit more limited.  timer2 also has a unique feature:
 * a period register.
 *
 * It will count up to the value in PR2 then wrap back down to zero, 
 * instead of always looping at 255.  This makes it easy to change the 
 * frequency.
 * 
 * We're changing the period register as we go, causing the frequency to
 * increase and decrease...  Hook up a piezo speaker to R0 and you'll hear it!
 */
#define __16f628a
#include "pic16f628a.h"
#include "tsmtypes.h"
//#include "tsmpic.h"
 
// Set the __CONFIG word:
// I usually set it to _EXTCLK_OSC&_WDT_OFF&_LVP_OFF&_DATA_CP_OFF&_PWRTE_ON
Uint16 at 0x2007  __CONFIG = CONFIG_WORD;
 
static void Intr(void) interrupt 0
{
	static Uint8 dir=0;
	if(TMR2IF)
	{
		TMR2IF=0;

		if(dir)	// Increase period
		{
			if(PR2 != 0xff)	PR2++;
			else		dir=0;
		}
		else	// decrease period
		{
			if(PR2 != 0x00)	PR2--;
			else		dir=1;
		}

		PORTA++;	// Toggle the state of the LSB of the port bits

	}
//	GIE=1;		// Globally enable interrupts.
			/** We don't need to do this ourselves since
			 *  the compiler ALWAYS ADDS THIS FOR US
			 *  in interrupt functions!
			 *  If you try and DISable interrupts in an
			 *  interrupt function it WON'T WORK since
			 *  the compiler ALWAYS turns them back ON!
			 */
}

void main(void)
{
	TRISA = 0x00;	// All Port A latch outputs are enabled.

#ifdef  __16f628a	// Only compile this section for PIC16f628a
	CMCON = 0x07;	/** Disable comparators.  NEEDED FOR NORMAL PORTA
			 *  BEHAVIOR ON PIC16f628a!
			 */
#endif

	T2CON=0x02;	// Prescaler to 1:16
	PR2=0xff;	// Maximum period
	PEIE=1;		// Enable peripheral interrupts
	TMR2IE=1;	// Enable timer 2 interrupts
	GIE=1;		// Enable interrupts globally
	TMR2ON=1;	// Enable timer2

/*	T0CS = 0;	// Clear to enable timer mode.
	PSA = 0;	// Clear to assign prescaler to Timer 0.

	PS2 = 1;	// Set up prescaler to 1:256.  
	PS1 = 1;
	PS0 = 1;

	INTCON = 0;	// Clear interrupt flag bits.
	GIE = 1;	// Enable all interrupts.

	T0IE = 1;	// Set Timer 0 to 0.  
	TMR0 = 0;	// Enable peripheral interrupts.*/

	// Loop forever.  
	while(1);
}  

