/******************************************************************************
*       Copyright (C) 2005 Freescale Semiconductor, Inc.
*       All Rights Reserved
*
* Filename:     DEMO9S08QG8_APP.c
* Author:       rxlr10
* Revision:     1.0
*
* Description:  This code is intended for use with the DEMO9S08QG8 demo board.
*               Connecting a serial cable from the DEMO9S08QG8 to a PC with a
*               Terminal emulation rpogram running allows the user to interact 
*               with the MCU and try out several of the features of the 
*               MC9S08QG8: the ICS, TPM, MTIM, RTI, STOP, ACMP, and ADC. 
*
* Notes:        Also serves as an example for the 9S08QG8 demo board.
*               Created using CodeWarrior 5.0 for HC(S)08.
******************************************************************************/

#include <hidef.h> /* for EnableInterrupts macro */
#include <string.h> /* for EnableInterrupts macro */
#include "derivative.h" /* include peripheral declarations */
#include "demo9S08QG8.h" /* include demo board declarations */
#include "DEMO9S08QG8_APP.h" /* include peripheral declarations */

volatile byte _NVICSTRM;  // instantiate the nonvolatile ICS Trim Register

void InitSysOpts() {
  SOPT1 = SOPT1val;       // enable COP, STOP and BKGND
  SOPT2 = SOPT2val;       // select cop clk
  SPMSC1 = SPMSC1_LVD_ON; // enable LVD as int, disabled in stop
  flag_stop1 = 0;
  flag_stop2 = 0;
  if (SPMSC2_PDF) {		   // Check if recovering from stop1
    flag_stop1 = 1;
    SPMSC2 = 0x06;		   // Reconfigure MCU for stop1 mode
  }
  if (SPMSC2_PPDF) {	   // Check if recovering from stop2
    flag_stop2 = 1;
    SPMSC2 = 0x07;		   // Reconfigure MCU for stop2 mode
  }
} //end InitSysOpts

void InitPorts() {
  // Enable pull-ups on all input pins
  PTAPE = 0xFF;
  PTBPE = 0xFF;
  
}	//end InitPorts

void InitRTI() {
//  SRTISC = 0b01110001;
  SRTISC = 0b01110000; //disable RTI while debugging
/*           ||||||||
             |||||+++-- RTIS = RTI delay select: 001=8 msec
             ||||+----- unimplemented
             |||+------ RTIE = RTI int enable: 1=enabled
             ||+------- RTICLKS = RTI clock select: 1=external src
             |+-------- RTIACK = RTI flag acknowledge
             +--------- RTIF = RTI flag
*/
}

void InitIRQ() {
// Enable IRQ as interrupt
  IRQSC = 0b00010110;
/*            ||||||
              |||||+---- IRQMOD = IRQ detection mode: 0=edge only
              ||||+----- IRQIE = IRQ int enable: 1=enabled
              |||+------ IRQACK = IRQ int acknowledge: 1=clr IRQF
              ||+------- IRQF = IRQ flag
              |+-------- IRQPE = IRQ pin enable: 1=enabled
              +--------- IRQEDG = IRQ edge select: 0=falling/low
*/
} //end InitIRQ

void InitIRQ_pin() {
// Enable IRQ, but not interrupt
  IRQSC = 0b00010100;
/*            ||||||
              |||||+---- IRQMOD = IRQ detection mode: 0=edge only
              ||||+----- IRQIE = IRQ int enable: 1=enabled
              |||+------ IRQACK = IRQ int acknowledge: 1=clr IRQF
              ||+------- IRQF = IRQ flag
              |+-------- IRQPE = IRQ pin enable: 1=enabled
              +--------- IRQEDG = IRQ edge select: 0=falling/low
*/
} //end InitIRQ_pin

void InitKBI(byte KBIpin) {  
  KBIPE = KBIpin;       //enable KBI pin
  KBISC = 0x06;         //enable KBI int and clear KBF
} //end InitKBI
  
void InitSCI(word baud_div) {
  
  SCIBD = baud_div;     // set baud based on bus
  SCIC1 = 0x00;
} //end InitSCI
  
void feedCOP() {
  
  if (PTAD_PTAD5 == 1)
    SRS = 1;			  // feed cop
  if (SPMSC1_LVDF == 1) {
    PTBD = PTBD^0x10;     // toggle PTB4
    SPMSC1_LVDACK = 1;    // clear LVDF
  }
} //end feedCOP

void SendChar(char s_char) {
  byte dummy;	   // dummy var for reading SCIS1
  
  SCIC2 = 0x08;    // enable Tx
  dummy = SCIS1;   // 1st half of TDRE clear procedure
  SCID = s_char;   // 2nd half of TDRE clear procedure
  while(!SCIS1_TDRE){
    feedCOP();
  };
  while(!SCIS1_TC){
    feedCOP();
  };
  SCIC2_TE = 0;
} //end SendChar

char RecChar() {
  byte rec_char;

  if (SCIS1_RDRF)  // 1st half of RDRF clear procedure
    rec_char = SCID;  // 2nd half of RDRF clear procedure
  SCIC2_RE = 1;    // enable Rx
  while(!SCIS1_RDRF){
    feedCOP();
  };
  rec_char = SCID; // get recieved character
  SendChar(rec_char); // echo received character
  return SCID;
} //end RecChar  

void SendMsg(char msg[]) {
  byte ix=0;	   // String pointer
  byte dummy;	   // dummy var for reading SCIS1
  byte nxt_char;
  
  SCIC2 = 0x08;    // enable Tx
  dummy = SCIS1;   // 1st half of TDRE clear procedure
  nxt_char = msg[ix++];
  while(nxt_char != 0x00) {
    SCID = nxt_char; // 2nd half of TDRE clear procedure
    nxt_char = msg[ix++];
    while(!SCIS1_TDRE){
      feedCOP();
    };
  } //end while((SCI1D
  while(!SCIS1_TC){
    feedCOP();
  };
  SCIC2_TE = 0;
} //end SendMsg


char * num2asc(byte n) {
  n_str[0] = (n>>0x04)+0x30;  // convert MSN 'n' to ascii
  if(n_str[0]>0x39)           // if MSN is $a or larger...
    n_str[0]+=0x07;           // ...add $7 to correct
  n_str[1] = (n&0x0f)+0x30;   // convert LSN 'n' to ascii
  if(n_str[1]>0x39)           // if LSN is $a or larger...
    n_str[1]+=0x07;           // ...add $7 to correct
  n_str[2] = 0x00;            // add null
  return n_str;
} //end num2asc

byte asc2num(char n_asc) {
byte n;

  n = n_asc - 0x30;      //convert from ascii to int
  if(n > 0x09)           // if num is $a or larger...
    n -= 0x07;           // ...sub $7 to correct
  if(n > 0x0f)           // if lower case was used...
    n -= 0x20;           // ...sub $20 to correct
  if(n > 0x0f)           // if non-numeric character...
    n = 0x00;            // ...default to '0'
  return n;
} //end asc2num

// Function for switching to an external clock mode (FEE or FBE)
void ics_extclk(byte C1, byte C2) {

  ICSC2 = C2;														
  if (ICSC2_EREFS) {		        	// if ext ref selected...
    while (!ICSSC_OSCINIT) {			// ...wait for OSC to start
      feedCOP();						// feed COP while waiting
    }					            	
  }
  ICSC1 = C1;
  while (ICSC1_CLKS != ICSSC_CLKST) {}  // wait for clk state to match clk select
} //end ics_setup

// Function for switching to an internal clock mode (FEI or FBI)
void ics_intclk(byte C1, byte C2) {
byte i;

  if (NVICSTRM != 0xFF) {
    ICSTRM = NVICSTRM;					// load trim value if location not blank
  }
  ICSC1 = C1;
  for (i=0x10;i>0;i--){
    feedCOP();
  }
  ICSC2 = C2;														
  while (ICSC1_CLKS != ICSSC_CLKST) {}  // wait for clk state to match clk select
} //end ics_setup

void ics_init() {
  byte done = 0x00;
  
  while (!done) {
    SendMsg("\r\n ICS Setup Menu:\r\n");
    SendMsg("  1: ICS in FEI, BDIV=1 (set BAUD to 4800 bps)\r\n");
    SendMsg("  2: ICS in FEI, BDIV=2 (set BAUD to 4800 bps)\r\n");
    SendMsg("  3: ICS in FEI, BDIV=4 (set BAUD to 4800 bps)\r\n");
    SendMsg("  4: ICS in FEI, BDIV=8 (set BAUD to 4800 bps)\r\n");
    SendMsg("  5: ICS in FBI (set BAUD to 110bps)\r\n");
    SendMsg("  6: ICS in FBILP (set BAUD to 110bps)\r\n");
    SendMsg("\nSelect test number to execute: ");
    done = 0x01;
    switch (RecChar()) {
      case one: ics_intclk(0x04,0x00); InitSCI(fei1_spd); break;
      case two: ics_intclk(0x04,0x40); InitSCI(fei2_spd); break;
      case three: ics_intclk(0x04,0x80); InitSCI(fei4_spd); break;
      case four: ics_intclk(0x04,0xC0); InitSCI(fei8_spd); break;
      case five: ics_intclk(0x40,0x00); InitSCI(fbi_spd); break;
      case six: ics_intclk(0x40,0x08); InitSCI(fbi_spd); break;
      default: done = 0x00; SendMsg("\nInvalid ICS mode!!!\r\n");
    } //end switch
  } //end while
} //end ics_init

void tpm_init() {
  byte done = 0x00;
  
  while (!done) {
    SendMsg("\r\nTPM PWM Setup Menu:\r\n");
    SendMsg("  1: Busclk source\r\n");
    SendMsg("  2: XCLK source\r\n");
    SendMsg("  3: TCLK source (requires external clock input on TCLK pin)\r\n");
    SendMsg("\nSelect test number to execute: ");
    TPMMODH = 0x03;
    TPMMODL = 0xE7;
    TPMC1SC = 0x24;
    TPMC1VH = 0x01;
    TPMC1VL = 0xF4;
    done = 0x01;
    switch (RecChar()) {
      case 0x31: TPMSC = 0x08; break;
      case 0x32: TPMSC = 0x10; break;
      case 0x33: TPMSC = 0x18; break;
      default: done = 0x00; SendMsg("\nInvalid selection!\r\n");
    } //end switch
  } //end while
} //end tpm_init

// Initialize the TPM for a PWM output on channel 1
void TPM_PWM() {
  
    TPMMODH = 0x27;			// set period to x10,000
    TPMMODL = 0x09;
    TPMC1VH = 0x13;			// set duty cycle to x5,000
    TPMC1VL = 0x88;
    TPMC1SC = 0x24;			// set channel 1 for PWM
    TPMSC = 0x08;			// select bus clock and start timer
} //end tpm_init

// Initialize the MTIM for a s/w PWM at x100
void Set100x() {

  LED1 = OFF;					// init LED1 value
  LED1_DDR = 1;             //setup LED1 as output
  MTIMCLK = 0x00;           //src = busclk div 1
  MTIMMOD = 42;             //modulo = 50
  MTIMSC = 0x60;            //reset and start MTIM
} //end Set10x

void SetPS() {
  byte PS;
  char PS_asc;

  SendMsg("\r\nMTIM Prescaler:\r\n");
  SendMsg("  0  : ÷ 1\r\n");
  SendMsg("  1  : ÷ 2\r\n");
  SendMsg("  2  : ÷ 4\r\n");
  SendMsg("  3  : ÷ 8\r\n");
  SendMsg("  4  : ÷ 16\r\n");
  SendMsg("  5  : ÷ 32\r\n");
  SendMsg("  6  : ÷ 64\r\n");
  SendMsg("  7  : ÷ 128\r\n");
  SendMsg("  8-F: ÷ 256\r\n");
  SendMsg("  e  : Exit menu\r\n");
  SendMsg("\nEnter value: ");
  
  for (;;) {
    PS_asc = RecChar();
    if (PS_asc == exit | PS_asc == EXIT)
      break;
    PS = asc2num(PS_asc);
    if (PS > 0x0f) {
      SendMsg("\nInvalid selection!\r\n");
    } //end if
    else {
      MTIMCLK_PS = PS;
      break;
    } //end else
  } //end for
} //end SetPS

void SetMod() {
  byte MS[2], i, done = 0x00;
  char MS_asc[3];

  SendMsg("\r\nEnter MTIM Modulo hex value from 00-FF: ");
  for (;;) {
    i=0;
    MS_asc[i] = RecChar();
    while (MS_asc[i]!=enter) {
      MS_asc[++i] = RecChar();
    } //end while
    if (i==2) {
      MS[0] = asc2num(MS_asc[0]);
      if (MS[0] > 0x0f) {
        SendMsg("\r\nInvalid value!");
      } //end if
      else {
        MS[1] = asc2num(MS_asc[1]);
        if (MS[0] > 0x0f) {
          SendMsg("\r\nInvalid value!");
        } //end if
        else {
          MTIMMOD = (MS[0]<<4) + MS[1];
          break;
        } //end else
      } //end else
    } //end if
    else {
      SendMsg("\r\nInvalid value! Modulo not changed.\r\n");
      break;
    } //end else
  } //end for
} //end SetMod

void SetCS() {
  byte done = 0x00;
  
  SendMsg("\r\nMTIM Clock Select:\r\n");
  SendMsg("  0: BUSCLK\r\n");
  SendMsg("  1: XCLK\r\n");
  SendMsg("  2: TCLK, falling edge\r\n");
  SendMsg("  3: TCLK, rising edge\r\n");
  SendMsg("  e: Exit MTIM menu\r\n");
  SendMsg("\nSelect test number to execute: ");

  while (!done) {
    done = 0x01;
    switch (RecChar()) {
      case zero  : MTIMCLK_CLKS = 0; break;
      case one   : MTIMCLK_CLKS = 1; break;
      case two   : MTIMCLK_CLKS = 2; break;
      case three : MTIMCLK_CLKS = 3; break;
      default: done = 0x00; SendMsg("\r\nInvalid selection!\r\n");
    } //end switch
  } //end while
} //end SetCS

void mtim_init() {
  byte done = 0x00;
  
  while (!done) {
    SendMsg("\r\nMTIM Setup:\r\n");
    SendMsg("  1: 100X PWM from busclk\r\n");
    SendMsg("  2: Set prescalar\r\n");
    SendMsg("  3: Set modulo\r\n");
    SendMsg("  4: Set clock source\r\n");
    SendMsg("  5: Start MTIM\r\n");
    SendMsg("  6: Stop MTIM\r\n");
    SendMsg("  7: Reset MTIM\r\n");
    SendMsg("  e: Exit MTIM menu\r\n");
    SendMsg("\nSelect test number to execute: ");

    switch (RecChar()) {
      case one   : Set100x(); break;
      case two   : SetPS(); break;
      case three : SetMod(); break;
      case four  : SetCS(); break;
      case five  : MTIMSC_TSTP=0; break;
      case six   : MTIMSC_TSTP=1; break;
      case seven : MTIMSC_TRST=1; break;
      case exit  : done = 0x01; break;
      case EXIT  : done = 0x01; break;
      default: SendMsg("\r\nInvalid selection!\r\n");
    } //end switch
  } //end while
} //end mtim_init

void rti_cal() {
word start, finish;
byte M_start, M_finish;

  // Setup MTIM as free-running
  MTIMMOD = 0x0000;
  // Set prescalar to 7 for ~ 1 tick / 7.68 msec with XCLK input (32768Hz xtal)
  MTIMCLK = 0x17;
  // Reset and start MTIM
  MTIMSC = 0x20;
  // Setup TPM as free-running with XCLK input (expect 32768 xtal or XCLK=16384Hz)
  TPMMOD = 0x0000;
  // Set prescalar to 1 for ~ 1 tick / 60 usec
  TPMSC = 0x10;
  // Setup RTI for 1.024sec timeout with int 1kHz source and int disabled
  SRTISC = 0x47;
  M_start = MTIMCNT;
  start = TPMCNT;
  while (!SRTISC_RTIF) {
    feedCOP();
  }
  finish = TPMCNT;
  M_finish = MTIMCNT;
  SRTISC = 0x40;   // clr RTIF and turn RTI off
  // Expected ET if 1kHz on target = 0x4000
  RTI_act = finish - start;
  M_RTI_act = M_finish - M_start;
  SendMsg("\r\n*** RTI timed out in ");
  SendMsg(num2asc(RTI_act>>0x08));
  SendMsg(num2asc(RTI_act & 0xFF));
  SendMsg(" TPM cycles ***\r\n");
  SendMsg("*** 1 KHZ would be $4189 ***");
  SendMsg("\r\n*** RTI timed out in ");
  SendMsg(num2asc(M_RTI_act));
  SendMsg(" TPM cycles ***\r\n");
  SendMsg("*** 1 KHZ would be $85 ***");
} //end rti_cal


void rti_init() {
  byte done = 0x00;
  
  while (!done) {
    SendMsg("\r\nRTI Setup Menu:\r\n");
    SendMsg("  1: RTI Internal clk measure\r\n");
    SendMsg("  2: RTI On\r\n");
    SendMsg("  3: RTI Off\r\n");
    SendMsg("\nSelect test number to execute: ");
    done = 0x01;
    PTBDD_PTBDD3 = 1;     //set PTA3 as output
    switch (RecChar()) {
      case one: rti_cal(); break;
      case two: SRTISC = 0x57; break;
      case three: SRTISC = 0x40; PTBDD_PTBDD3 = 0; break;
      default: done = 0x00; SendMsg("\nInvalid selection!\r\n");
    } //end switch
  } //end while
} //end tpm_init
  

void enter_stop() {

  SendMsg("\r\nEntering stop mode\r\n");
  asm ("stop");
  SendMsg("\r\nExitted stop3 mode\r\n");
}	//end enter_stop

void stop_setup(byte mode) {

    switch (mode) {
      case 1 : SPMSC2 = 0x02; break;
      case 2 : SPMSC2 = 0x03; break;
      case 3 : IRQSC = 0x17; break;
    } //end switch
} //end stop_setup

void stop_init() {
  byte done = 0x00;
  
  while (!done) {

    SendMsg("\r\nStop Setup Menu:\r\n");
    SendMsg("  1: Configure for stop1\r\n");
    SendMsg("  2: Configure for stop2\r\n");
    SendMsg("  3: Configure for stop3\r\n");
    SendMsg("  4: Enter stop\r\n");
    SendMsg("  e: Exit Stop menu\r\n");
    SendMsg("\nSelect test number to execute: ");

    switch (RecChar()) {
      case one   : stop_setup(1); break;
      case two   : stop_setup(2); break;
      case three : stop_setup(3); break;
      case four  : enter_stop(); break;
      case exit  : done = 0x01; break;
      case EXIT  : done = 0x01; break;
      default: SendMsg("\r\nInvalid selection!\r\n");
    } //end switch
  } //end while
} //end stop_init

void acmp_init() {
  byte done = 0x00;
  word old_acmp_ic, delta_acmp_ic, delta_secs;
  
  while (!done) {

    SendMsg("\r\nAnalog Comparator Menu:\r\n");
    SendMsg("  1: Enable ACMP\r\n");
    SendMsg("  2: Disable ACMP\r\n");
    SendMsg("\nSelect test number to execute: ");

    done = 0x01;
    switch (RecChar()) {
      case one  : ACMPSC = acmp_rise; break;
      case two  : ACMPSC = 0x00; break;
      default: done = 0x00; SendMsg("\r\nInvalid selection!\r\n");
    } //end switch
  } //end while
  
  if (ACMPSC_ACME) {
    SOPT2_ACIC = 0x01;
    TPMSC = 0x00;						// tpm disabled
    TPMMODH = 0xFF;						// set timer modulo to...
    TPMMODL = 0xFE;						//...$FFFE
    TPMCNTL = 0x00;						// clear counter
    TPMC0SC = 0x4C;						// enable input capture w/ int
    TPMSC = 0x17;						// tpmclk = xclk/1286, int enabled
    MTIMSC_TSTP=1;                      // disable MTIM
  } else {
    SOPT2_ACIC = 0x00;
    TPMSC = 0x00;
  } //end if
  ACMP_IC = 0x0000;
  old_acmp_ic = 0x0000;
  SendMsg("\r\nAdjust RV1 or RZ1 to trigger comparator");
  while (ACMP_IC != 0xFFFF){
    ACMP_IC = 0xFFFF;
    SendMsg("\r\nPress SW1 or SW2 on DEMO9S08QG8 to exit");
    flag_acmp = 0;
    while(!flag_acmp) {
      if (SW1 == DOWN)
        flag_acmp = 1;
      if (SW2 == DOWN)
        flag_acmp = 1;
      feedCOP();
    } // end while
    SendMsg("\r\nTime since last ACMP toggle = $");
    delta_acmp_ic = ACMP_IC - old_acmp_ic;
    if (delta_acmp_ic>0x7A) {
      delta_secs = delta_acmp_ic/0x7A;
    } else {
      delta_secs = 1;
    }
    old_acmp_ic = ACMP_IC;
    SendMsg(num2asc(delta_secs >> 8));
    SendMsg(num2asc(delta_secs & 0xFF));
    SendMsg(" seconds");
  } //end while
} //end acmp_init
  
void ADC_Go(byte adc_chnl) {

  ADCSC1_ADCH = adc_chnl;
  Enter_Wait;
} //end ADC_Go

void adc_BGap(void) {

  SPMSC1_BGBE = 1;					 // Enable bandgap
  ADC_Go(0x1B);					     // Select bandgap input
  SendMsg("\r\nInternal bandgap = ");
  SendMsg(num2asc(ADC_val_H));
  SendMsg(num2asc(ADC_val_L));
  SendMsg("\r\n");
  SPMSC1_BGBE = 0;					 // Disable bandgap
} //end adc_BGap

void adc_meas(void) {
  
  ADC_Go(0);
  SendMsg("\r\nValue of RV1 (potentiometer) = ");
  SendMsg(num2asc(ADC_val_H));
  SendMsg(num2asc(ADC_val_L));
  ADC_Go(1);
  SendMsg("\r\nValue of RZ1 (photo sensor) = ");
  SendMsg(num2asc(ADC_val_H));
  SendMsg(num2asc(ADC_val_L));
  SendMsg("\r\n");
} //end adc_meas

void adc_init(void) {
  
  byte done = 0x00;
  ADCSC1 = 0x5F;  /* Enable interrupts 
                     Disable continuous conversions
                     Disable ADC by setting all ADCH bits */
  ADCSC2 = 0x00;  /* Select S/W trigger
         						 Disable compare function */
  ADCCFG = 0x0B; 	/* ADIV=input clock/8
                     ADLSMP=long sample time
                     MODE=10bit conversion
                     ADICLK=bus clock */
  APCTL1 = 0x0E;  // Enable pins 1-3 as ADC inputs
  
  while (!done) {

    SendMsg("\r\nADC Menu:\r\n");
    SendMsg("  1: Meas RV1 & RZ1\r\n");
    SendMsg("  2: Meas Internal Bandgap\r\n");
    SendMsg("  e: Exit ADC menu\r\n");
    SendMsg("\nSelect test number to execute: ");

    switch (RecChar()) {
      case one   : adc_meas(); break;
      case two   : adc_BGap(); break;
      case exit  : done = 0x01; break;
      case EXIT  : done = 0x01; break;
      default: SendMsg("\r\nInvalid selection!\r\n");
    } //end switch
  } //end while

  APCTL1 = 0x00;  // Disable all pins as ADC inputs
  ADCSC1 = 0x1F;  // Disable ADC by setting all ADCH bits 
  
} //end adc_init

/********************************************************************
9S08QG9 systems tests:
********************************************************************/
void main(void) {

  RAMSRS = SRS;							  //Save SRS vaue to RAM
// Initializations
  InitPorts();
  InitSysOpts();
  ics_intclk(0x04,0x00);                  //set ICS for FEI mode
  InitKBI((SW1_MASK+SW2_MASK));           //init KBIP as falling edge int
  InitSCI(fei1_spd);                      //init SCI fr 9600 baud in FEE mode

// Print cause of last reset
  SendMsg("\fSystem Reset Status Register = ");
  SendMsg(num2asc(RAMSRS));
  SendMsg("\r\n");
  if (RAMSRS_COP)
    SendMsg("\r\n*** COP Reset Occurred ***\r\n");
  if (RAMSRS_LVD)
    SendMsg("\r\n*** LVD Reset Occurred ***\r\n");
  if (RAMSRS_ILAD)
    SendMsg("\r\n*** Illegal Address Reset Occurred ***\r\n");
  if (RAMSRS_ILOP)
    SendMsg("\r\n*** Illegal Opcode Reset Occurred ***\r\n");
  if (RAMSRS_PIN)
    SendMsg("\r\n*** Pin Reset Occurred ***\r\n");
  if (RAMSRS_POR)
    SendMsg("\r\n*** POR Reset Occurred ***\r\n");
  
  
  if (flag_stop1)
    SendMsg("\r\n*** Exitted stop1 ***\r\n");
  if (flag_stop2)
    SendMsg("\r\n*** Exitted stop2 ***\r\n");

  Set100x();
  TPM_PWM();
  EnableInterrupts;
  
/*
Perform SCI link test...
*/
  SendMsg("\r\nWelcome to the MC9S08QG8 Demo Application\r\n");
  SendMsg("V1.0\r\n");
  
// Main program loop
  for(;;) {
    SendMsg("\r\nMain Test Menu:\r\n");
    SendMsg("  1: ICS setup\r\n");
    SendMsg("  2: TPM PWM setup\r\n");
    SendMsg("  3: MTIM setup\r\n");
    SendMsg("  4: RTI setup\r\n");
    SendMsg("  5: STOP test\r\n");
    SendMsg("  6: ACMP test\r\n");
    SendMsg("  7: ADC test\r\n");
    SendMsg("\nSelect number to execute: ");
    switch (RecChar()) {
      case one  : ics_init();  break;
      case two  : tpm_init();  break;
      case three: mtim_init(); break;
      case four : rti_init();   break;
      case five : stop_init();   break;
      case six  : acmp_init();   break;
      case seven: adc_init();   break;
      default: SendMsg("\nInvalid selection\r\n");
    } //end switch
  } //end for(;;)
} //end main


/*********************************************************************
**  Interrupt Service Routines
*********************************************************************/
interrupt 23 void   RTI_ISR(void) {
  SRTISC |= 0x40;  // clear RTIF
  PTBD ^= 0x08;     //toggle PTB3
}

interrupt 18 void   KBI_ISR(void) {
byte    x,y;
  for(x=0;x<0xff;x++){
     for(y=0;y<0xff;y++){}		// debounce pin
  }
  KBISC_KBACK = 1;       // clear IRQF
}

interrupt 19 void   ADC_ISR(void) {
  ADC_val_H = ADCRH;
  ADC_val_L = ADCRL;
}

interrupt 12 void   MTIM_ISR(void) {
  MTIMSC_TOF=0;          // clear TOF
  if (LED1)
    LED1 = ON;
  else
    LED1 = OFF;
}

interrupt 5 void   TPMC0_ISR(void) {
  flag_acmp = 1;
  ACMP_IC = TPMCNT;
  TPMC0SC_CH0F = 0;
}

interrupt 3 void   LVD_ISR(void) {
  PTBD = PTBD^0x10;      // toggle PTB4
  SPMSC1_LVDACK = 1;     // clear LVDF
}

interrupt 2 void   IRQ_ISR(void) {
byte    x,y;
  for(x=0;x<0xff;x++){
     for(y=0;y<0xff;y++){} // debounce pin
  }
  IRQSC_IRQACK = 1;      // clear IRQF
}

