// System.c

#include "defs.h"

static void IRQ_Handler(void)
{
  if (IRQSTA & WAKEUP_TIMER_BIT) {
    T2CON = 0;	// Disable T2
	T2CLRI = 0;	// Clear T2 interrupt

    // Standard POWCON Write Sequence
    POWKEY1 = 0x01;
    POWCON = 0x03;	// Set Core working mode, CD = 3
    POWKEY2 = 0xF4;	
  } 
}


void InitController(void)
{
#ifdef ExternalCrystal
  int t2val_old;
#endif

  IRQ = IRQ_Handler;

#ifdef ExternalCrystal
  // WAKEUP (T2) Timer settings
  t2val_old = T2VAL;

  // Select External Crystal
  // 5 periodes of 32kHz internal oscillator.  T >= 120us
  T2LD = 5;
  // Enable the Timer2 interrupt
  T2CON = 0x480;
  // Ensures timer value loaded
  while ((T2VAL == t2val_old) || (T2VAL > 3))
    IRQEN = 0x10;	// enable T2 interrupt
	
  // Standard PLLCON Write Sequence
  PLLKEY1 = 0xAA;
  PLLCON = 0x01;	// External Crystal
  PLLKEY2 = 0x55;
  
  // Standard POWCON Write Sequence
  POWKEY1 = 0x01;
  POWCON = 0x27;	// Set Core into NAP mode, CD = 7
  POWKEY2 = 0xF4;	
#endif

  GP0DAT = 0x80000000;		//	Configure P0.7 as output (TXEN)
  GP1DAT = 0x04000000;		//	Configure P1.2 as output (PowerEN)

  // Timer1: HCLK + Count Up + Enable + Free Running + Binary + SourceClock/1
  T1CON = 0x180;

  // DAC0, DAC1: Enable + Vref(2.5V) reference
  DAC1CON = DAC0CON = 0X12;
//  DAC0DAT = 0xFFF0000;
//  DAC1DAT = 0xFFF0000;
}

void delay(u32 duration /*us*/)
{
  u32 i;

  i = (duration-1)*TiksPerUs;
  if ((u32)T1VAL > 0x80000000L) {
    i += T1VAL - 0x80000000L;
	while ((u32)(T1VAL - 0x80000000L) < i);
  }
  else {
    i += T1VAL;
    while (T1VAL < i);
  } 
}
