/* 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=10, per_on3=10, helper=0,cntflag=0;


/* Prototypes */
void initoc(void);
void rtoc2(void);
void rtoc3(void);
void cnts2(void);
void cnts3(void);
void RTIINTR (void);


void main(void)
{
 	int cnttime;
	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|0x03;
	
	initoc();
	
	cnts2();
	cnts3();
	
	while(1)
	{	 
		 
	 	 if (helper == 1){
		 	per_on2=per_on3=75;
		 	cnts2();
		 	cnts3();
		 	
	 		motcont = 0x00;
		 }	 
		 else if (helper == 5){
		 	per_on2=per_on3=40;
		 	cnts2();
		 	cnts3();
		 	//printf("%x   %x   %x    %x\n",OC2hi,OC2lo,OC3hi,OC3lo); 
	 		motcont = 0x03;
		 }	 
		else if  (helper == 10){ 
			 TMSK1=0x00;
    		 PORTA=0x00;
			 printf("%d\n",helper);
			 }	 
    }

	
}

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 + OC2lo;
		PORTA = PORTA | 0x40;
		}
	else
		TOC2 = TOC2 + OC2hi;
		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 + OC3lo;
		PORTA = PORTA | 0x20;
	}	
	else
		TOC3 = TOC3 + OC3hi;
		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++;
		   if (cntflag == 31){
		   cntflag=0;
		   helper++;
		   if (helper == 15)
		      helper=0;
		   }
	asm("   rti");
} 