#include <mc9s12dp256.h>		


__interrupt void RealTimeInterrupt(void); 


static volatile unsigned char rtiCnt;		/* to count number of RTIs */



void main(void)
{
  /* set up Port B */
  DDRB = 0xFF;				/* set portb pins all to output */
  PORTB = 0x00;         /* turn Port B LEDs off */

  /* Set up the A/D converter and start it running; we use 8 bit resolution. Note that
  *  the ATD registers have a "0" signifier - thus we have ATD0CTL2 instead of ATDCTL2 as
  *  used in some parts of the HCS12 hardware manual */
  ATD0CTL2 = 0x80;      /* turn on ADC */
  ATD0CTL3 = 0x08;      /* 1 AD conversion/sequence */
  ATD0CTL4 = 0xEB;      /* 8 bit, 16 AD clocks/conversion, 1 MHz clock */
  ATD0CTL5 = 0x27;      /* left justify, unsigned, sample only specified channel */

  /* set up RTI */
  RTICTL = 0x31;			/* (2*2^12)/(4x10^6) = 2.048 ms per RTI */
  CRGINT |= 0x80;			/* enable RTI interrupt */
  rtiCnt = 0;				/* RTI counter to 0 */
  asm("cli");				/* enable global interrupts */

  for (;;) {				/* our infinite loop */

    if (rtiCnt == 10) 	 /* check the AD registers every 20 msec */
    {

      /* light LEDs according to range in AD result register; since 8 bit,
	  *  we need only to look at the high byte, ATD0DR0H, of the result register*/

      if(ATD0DR0H <= 0x20)	/* no LEDs lit if less than $20 */
       PORTB = 0x00;
      if(ATD0DR0H > 0x20)
       PORTB = 0x01;
      if(ATD0DR0H > 0x40)
       PORTB = 0x03;
      if(ATD0DR0H > 0x60)
       PORTB = 0x07;
      if(ATD0DR0H > 0x80)
       PORTB = 0x0f;
      if(ATD0DR0H > 0xa0)
       PORTB = 0x1f;
      if(ATD0DR0H > 0xc0)
       PORTB = 0x3f;
      if(ATD0DR0H > 0xe0)
       PORTB = 0x7f;
      if(ATD0DR0H == 0xff)   /* all LEDs lit if max value $ff */
       PORTB = 0xff;
      
      rtiCnt = 0;			/* reset rti counter */
    }
  }
} /* end main() */


__interrupt void RealTimeInterrupt(void)
{
  rtiCnt++;					/* increment the counter        */
  CRGFLG = 0x80;			/* clear rti flag               */
} /*end RealTimeInterrupt() */


/***** end c_adc_demo.c ****/