// Copyright (c) 2001-2004 Rowley Associates Limited.
//
// This file may be distributed under the terms of the License Agreement
// provided with this software.
//
// THIS FILE IS PROVIDED AS IS WITH NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
////////////////////////////////////////////////////////////////////////////////
//
//                 Analog ADuC7020 Timer Interrupt Example
//
// Description
// -----------
// This example demonstrates setting up interrupt handlers and timers.
//
////////////////////////////////////////////////////////////////////////////////

#include <targets/ADuC7020.h>

#define TIMER0_INT 2
#define TIMER1_INT 3

static int timer0Count, timer1Count;

static void
ledInit()
{
  GP4CON &= ~(3 << 16); /* Set P4.2 to GPIO function */
  GP4DAT |= 1 << (2 + 24); /* Set P4.2 to output */
}

static void
ledOn()
{
  GP4CLR = 1 << (2 + 16);
}

static void
ledOff()
{
  GP4SET = 1 << (2 + 16);
}

void irq_handler(void) __attribute__ ((interrupt ("IRQ")));

void
irq_handler(void)
{
  unsigned int status = IRQSTA;
  if (status & (1 << TIMER0_INT))
    {
      if (++timer0Count % 2)
        ledOn();
      else
        ledOff();
      /* Clear the timer 0 interrupt */
      T0CLRI = 0;
    }
  if (status & (1 << TIMER1_INT))
    {
      ++timer1Count;
      T1CLRI = 0;
    }
}

int
main(void)
{
  ledInit();

  IRQEN |= 1 << TIMER0_INT; /* Timer 0 generates IRQ interrupts */
  IRQEN |= 1 << TIMER1_INT; /* Timer 1 generates IRQ interrupts */

  T0LD = 0;
  T0CON = 0x88; /* Timer 0 enable, free-running, core clock / 256 */

  T1LD = 0;
  T1CON = 0x88; /* Timer 1 enable, free-running, core clock / 256 */

  /* Enable Interrupts */
  __ARMLIB_enableIRQ();
  
  while (timer0Count < 5 || timer1Count < 5);

  return 0; 
}
