/* C Listing 11.4 */

#include <hc11.h>	/* Include register definitions */
#include <stdio.h>
#define motcont *(unsigned char volatile *)(0xB590)
#define linetrack *(unsigned char volatile *) (0XB5A0)


/* Declarations */
unsigned int OC2hi, OC2lo, OC3hi, OC3lo;	/* Duty cycle data */
unsigned int T_counts=0x4e20, per_on2=10, per_on3=10, cntflag=0;


/* Prototypes */
void initoc(void);
void rtoc2(void);
void rtoc3(void);
void cnts2(void);
void cnts3(void);
//void RTIINTR (void);


void main(void)
{
 	
	setbaud(BAUD9600);
	INTR_OFF();
	/* set up jump vector for buffalo */
	asm("	ldaa #$7e");
	asm("	staa $dc");
	//asm("	staa $eb");
	asm("	staa $d9");
	asm("	ldd #_rtoc2");
	asm("	std $dd");
	asm("	ldd #_rtoc3");
	asm("	std $da");
	/*asm("	ldd #_RTIINTR");
	asm("	std $ec");*/
	OC2hi = 0x3e8;
	OC2lo = 0x3e8;
	OC3hi = 0x3e8;
	OC3lo = 0x3e8;
	/*TMSK2=0x40;
	PACTL=PACTL&0xFC;
	PACTL=PACTL|0x00;*/
	
	initoc();
	cnts2();
    cnts3();
	motcont = 0x03;
	while(1)
	{	
		
	if ((TFLG2 & 0x80) == 0x80){
		 TFLG2 = 0x80; 
		 printf("%d    %d     %d\n", per_on2, per_on3,OC2hi);
		 per_on2 += 1;
		 per_on3 += 1;
		 
		 if (per_on2>90)
		 	per_on2 = 90;
		 if (per_on3>90)
		 	per_on3 = 90;
			
		 cnts2();
		 cnts3();
	}	 
    }

	
}

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) == 0x00){ 
		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) == 0x00) {
		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;
}	

/*void RTIINTR (void)
{	
	TFLG2=0x40;
	
	cntflag++;

	asm("   rti");
} */