// filename ******** Main.C ************** 
// MC9S12C32 interrupt example   
// RTI (Real Time Interrupt) generates periodic interrupts
// Jonathan W. Valvano 2/8/04

#include <hidef.h>      /* common defines and macros */
#include <mc9s12c32.h>     /* derivative information */
#pragma LINK_INFO DERIVATIVE "mc9s12c32"

unsigned short Count;		// number of RTI interrupts
int Ack;

int i;

// Ack=1  means foreground is waiting for background
// Ack=0  means background is waiting for foreground
void interrupt 7 handler(){
  PTT |= 0x01;       // debugging
  CRGFLG = 0x80;     // acknowledge, clear RTIF flag
  if(Ack==1){        // software handshake
    Ack = 0;         // means RTI interrupt happened
  }
  Count++;           // number of interrupts
  PTT &= ~0x01;      // debugging
}

//*******************RTIinit*************
// initialize RTI interrupts every 4096us or 244.14Hz
// inputs: none
// outputs: none
// will enable interrupts
// PortT bits 1,0 are for debugging
void RTIinit(void){
  asm sei        // Make ritual atomic 
  DDRT |= 0x03;  // PortT bit 1,0 are outputs to LEDs
  PTT = 0x00;
  CRGINT = 0x80; // RTIE=1 enable rti
  RTICTL = 0x33; // period=250ns*4096*4=4096us or 244.14Hz
  Count = 0;     // interrupt counter
/*  base clock is OSCCLK=250nsec
RTR[6:4] Real Time Interrupt Prescale Rate Select Bits
  000 off
  001 divide by 1024
  010 divide by 2048
  011 divide by 4096
  100 divide by 8192
  101 divide by 16384
  110 divide by 32768
  111 divide by 65536
RTR[3:0] Real Time Interrupt Modulus Counter Select Bits
 0000 divide by 1
 0001 divide by 2
 0010 divide by 3
 0011 divide by 4
 0100 divide by 5
 0101 divide by 6
 0110 divide by 7
 0111 divide by 8
*/  
  Ack = 1;       // means foreground is ready
  asm cli
}




void delay(int num)
{
   
    while (num>0)       
    {
        i = 1000;       
        while (i > 0)
        {
            i = i-1;
        }
        num = num - 1;
    }
}

	 

void main(void)
{
  RTIinit();
  
  /*delay(100);  	 */
  
  asm wai
  
  
  
  
  for(;;){
    if(Ack==0){    // software handshake
      Ack = 1;     // means main has happened
      PTT ^= 0x02; // toggle bit 1
    }
  }
}
