/**
 * An example of use of the timer1 counter and the 32khz crystal oscillator.
 *
 * The pic16f628a can hang a standard 32.768Khz watch crystal off of 
 * pins B6 and B7!  (It's not intended for any other crystals.)
 *
 * By setting a few register bits, it will turn these pins into a 
 * crystal oscillator capable of directly feeding Timer1.
 * The oscillator even seems to work without the fiddly capacitors,
 * though the crystal's accuracy is likely horrendous without them.
 *
 * Timer1 is a 16-bit counter spread across two registers,
 * TMR1L and TMR1H.  When TMR1L overflows from 255 to 0, TMR1H is
 * incremented.  When TMR1H overflows, if the chip is so configured,
 * it will generate an interrupt.
 *
 * The point, beyond precise timing, is that the external oscillator 
 * operates during asleep, will cause timer1 to count during sleep, and
 * even generate overflow interrupts during sleep, waking the chip.
 *
 * We're not using any interrupts or anything in this example -- just 
 * turning on the B6-B7 crystal oscillator, and running and endless loop
 * copying TMR1L into PORTB and TMR1H into PORTA.  This provides a 
 * variety of frequencies from 16Khz to 0.5Hz on the following pins:
 *
 *	B0:	16	KHz
 *	B1:	8	KHz
 *	B2:	4	KHz
 *	B3:	2	Khz
 *	B4:	1	Khz
 *	B5:	512	Hz
 *	B6:	Crystal oscillator!
 *	B7:	Crystal oscillator!
 *
 *	A0:	4	Hz
 *	A1:	2	Hz
 *	A2:	1	Hz
 *	A3:	0.5	Hz
 *	A4:	64	Hz
 *	A5:	Reset 		(would be 32 Hz)
 *	A6:	CLKOUT		(would be 16 Hz)
 *	A7:	8	Hz	(sometimes CLKIN instead)
 *
 *	When the oscillator is operating, you should be able to see
 *	a very weak 32-khz sine wave on pin 12 with your oscilloscope.
 *	Very weak indeed -- if you don't set your scope probe to 10x 
 *	impedance, the oscillator may actually stop when you probe it!
 *
 * See 7.0:  Timer1 module in the pic16f628a datasheet for detailed 
 * info.
 */
#define __16f628a
#include "pic16f628a.h"
#include "tsmtypes.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;

void main(void)
{
	TRISA = 0x00;	// All Port A latch outputs are enabled.
	TRISB = 0x00 | 0x80 | 0x40; // B7 and B6 should be inputs.

#ifdef  __16f628a	// Only compile this section for PIC16f628a
	CMCON = 0x07;	/** Disable comparators.  NEEDED FOR NORMAL PORTA
			 *  BEHAVIOR ON PIC16f628a!
			 */
#endif

	T1CKPS0=0;	// Set Timer1 prescaler to 1:1
	T1CKPS1=0;

	T1OSCEN=1;	// Enable crystal oscillator across B6/B7
	NOT_T1SYNC=1;	// Do not synchronize external clock
	TMR1CS=1;	// Use external clock
	TMR1ON=1;	// Enable timer 1

	// Loop forever.  
	while(1)
	{
		// TMR1H goes on PORTA with high and low swapped.
		// This lets us output the 1Hz signal on a pin that's
		// not weird in any way.
		PORTA = (TMR1H >> 4) | (TMR1H << 4) ;

		PORTB=TMR1L;	// TMR1L goes on PORTB direct.
	}
}  
