/*
	MGPRTPIO.C
	
	BL14xx/MicroG or BL15xx/MicroG2
	
	Use PRT0 to generate a square wave out of PIO port A.
	
	Bit 0 (PA0 - H3 pin2) has the shortest period (highest frequency).
	Bit 1 (PA1 - H3 pin3) has double (half) the period of bit 0.
	Bit 2 (PA2 - H3 pin4) has double (half) the period of bit 1.
	etc...
*/

char pioadata;

main()
{
	outport(PIOCA, 0xcf);      // set for mode 3
	outport(PIOCA, 0x00);      // all bits are outputs
	outport(PIODA, 0x00);      // set all outputs to zero

	pioadata = 0x00;
	set_timer0(10);            // 10 millisecond load
	
	while(1)
	{
		hitwd();
		runwatch();
	}
}

// Load and start timer0 to interrupt periodically for the specified 
// milliseconds.

int set_timer0(unsigned int milliseconds)
{
unsigned int load_value;

	if(milliseconds >= 200) milliseconds = 200;     
																// limit to 200 millisecond
	load_value = (unsigned int) (milliseconds*307.2);

	DI();

		hitwd();
	// timer0 interrupt every (load_value*20)/6144000 

	outport(TCR, inport(TCR) & '\B11101110');    // inhibit TIMER0 interrupt
	outport(TMDR0L, load_value & 0xff);
	outport(TMDR0H, (load_value >> 8) & 0xff);
	outport(RLDR0L, load_value & 0xff);
	outport(RLDR0H, (load_value >> 8) & 0xff);

	outport(TCR, inport(TCR) | '\B00010001');
	EI();
}

#INT_VEC PRT0_VEC timer0

interrupt timer0()
{
	inport(TCR);            // reset the interrupt
	inport(TMDR0L);         // reset the interrupt
	pioadata++;             // increment the data
	outport(PIODA, pioadata);  // output to PIOA port
}

