// filename ******** Main.C **************
// MC9S12C32 blinking LED using interrupts
// The RTI and TOC3 interrupt service routines output a char to the SCI
// and flash an LED on the "Docking Module" or "School Board"
// Steven LAmb: May 3, 2004

#include "9s12c32.h"     // Register Info
#include "main.h"        // prototypes and macros
#include "sci.h"         // serial control interface

void main(void) {
  SCI_Init(19200);	// standard baud rate
  OutCRLF;
  SCI_OutString("Technological Arts 9S12C32, RTI/TOC3 test  03/03/04 -SRL");
  OutCRLF;

  TC3init();
  RTIinit();
  for(;;);
}

// initialize TOC3 interrupts every XXus
void TC3init(void){
  unsigned short n=0;
  DISABLE_INTERRUPTS;       // DO NOT INTERRUPT INIT ROUTINE
  DDRT |= TC3LED;           // set PORTT:OC3LED to output
  TIOS |= BIT3;             // activate TC3 as output compare
  TSCR1 = BIT7;             // Enable TCNT
  TSCR2 = BIT2|BIT1|BIT0;   // divide by 128 TCNT prescale, TOI disarm
                            // divide by prescale = 2^TSCR2[2:0]
                            // ie TSCR2=0x07 -> prescale divide by 2^7 = 128
  TIE  |= BIT3;             // arm TC3
  TC3   = TCNT + DELAY3;    // Interrupt after delay counts
  ENABLE_INTERRUPTS;
}

// Interrupt Handler routine for TOC3
void __attribute__((interrupt))
TC3Handle(void){
    TFLG1 = BIT3;              // acknowledge interrupt from OC3
    SCI_OutString (" 3 ");     // message to say we are here
    PORTT ^= TC3LED;           // toggle LED
    TC3 += DELAY3;             // Set new interrupt interval
}

// initialize RTI interrupts every 4096us
void RTIinit(void){
  DISABLE_INTERRUPTS;   // DO NOT INTERRUPT INIT ROUTINE
  DDRT   |= RTILED;     // set PORTT:RTILED to output
  CRGINT = BIT7;        // enable RTI
  RTICTL = 0x77;        // freq = 4Mhz / (64*1024)          / 8 = 7.63Hz
                        // freq = 4MHz / 2^(RTICTL(6:4)) * 1024 / (RTICTL(3:0)+1)
                        // Note: (RTICTL(6:4) = 0 turns interrupts off
  ENABLE_INTERRUPTS;
}

// Interrupt Handler routine for RTI
void __attribute__((interrupt))
RTIHandle(){
   CRGFLG = 0x80;                 // acknowledge RTI
   SCI_OutString("R");         //message to say we are here
   PORTT ^= RTILED;            // toggle RTILED
}


