/* C Listing 11.4 */

#include <hc11.h>	/* Include register definitions */
#include <stdio.h>
#define motcont *(unsigned char volatile *)(0xB590)



/* Declarations */
unsigned int OC2hi, OC2lo, OC3hi, OC3lo;	/* Duty cycle data */
unsigned int T_counts=0x4E20, per_on2=20, per_on3=20, stopper=0;


/* Prototypes */
void initoc(void);
void rtoc2(void);
void rtoc3(void);
void cnts2(void);
void cnts3(void);



void main(void)
{
 	
	
	setbaud(BAUD9600);
	INTR_OFF();
	/* set up jump vector for buffalo */
	asm("	ldaa #$7e");
	asm("	staa $dc");
	asm("	staa $d9");
	asm("	ldd #_rtoc2");
	asm("	std $dd");
	asm("	ldd #_rtoc3");
	asm("	std $da");
	
	
    initoc();
	cnts2();
	cnts3();

	
	while(stopper <= 500)
	{		
		
		while (stopper <= 250){
		TMSK1 = 0x00;
		PORTA = 0x00;
		stopper ++;
		printf("%d\n", stopper);
		}
		TMSK1 = 0x60;
		cnts2();
		cnts3();
		stopper ++;
	}
}

void initoc(void)
/* Initialize OC2 */
{
	TOC2 = TCNT;
	TOC3 = TCNT;
	TCTL1 = 0x00;
	TFLG1 = 0x60;
	TMSK1 = 0x60;
	INTR_ON();
}

void rtoc2(void)
/* Interrupt Service Routine for OC2 PWM */
{   
	if ((PORTA & 0X40) == 0){ 
		TOC2 = TOC2 + OC2hi;
		PORTA = PORTA | 0x40;
		}
	else{
		TOC2 = TOC2 + OC2lo;
		PORTA = PORTA & 0xBF;
		}
	//TCTL1 = TCTL1 ^ 0x40;	/* invert OL2 to toggle next OC2 edge */
	TFLG1 = 0x40;	/* Clear flag OC2F */
	asm("	rti");	/* This is an interrupt service routine */
}

void rtoc3(void)
{	
	if ((PORTA & 0X20) == 0) {
		TOC3 = TOC3 + OC3hi;
		PORTA = PORTA | 0x20;
	}	
	else{
		TOC3 = TOC3 + OC3lo;
		PORTA = PORTA & 0xDF;
	}
	//TCTL1 = TCTL1 ^ 0x10;	/* invert OL2 to toggle next OC2 edge */
	TFLG1 = 0x20;	/* Clear flag OC2F */
	asm("	rti");	/* This is an interrupt service routine */
}
void cnts2 (void)
{
	OC2hi=T_counts * (float)per_on2/100;
	OC2lo=T_counts - OC2hi;
}

void cnts3 (void)
{
  	OC3hi=T_counts * (float)per_on3/100;
	OC3lo=T_counts - OC3hi;
}	


