// 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.
//
////////////////////////////////////////////////////////////////////////////////
//
//               theARMPatch LPC SBC2 Timer Interrupt Example
//
// Description
// -----------
// This example demonstrates a simple interrupt handler and setting up a timer.
//
////////////////////////////////////////////////////////////////////////////////

#include <targets/LPC22xx.h>

static int timer0Count, timer1Count;

static void timer0ISR(void) __attribute__ ((interrupt ("IRQ")));

static void
timer0ISR(void)
{
  ++timer0Count;
  /* Clear the timer 0 interrupt */
  T0IR = 0xFF;
  /* Update VIC priorities */
  VICVectAddr = 0;
}

static void timer1ISR(void) __attribute__ ((interrupt ("IRQ")));

static
void
timer1ISR(void)
{
  ++timer1Count;
  /* Clear the timer 1 interrupt */
  T1IR = 0xFF;
  /* Update VIC priorities */
  VICVectAddr = 0;
}

int
main(void)
{
  /* Timer 0 interrupt is an IRQ interrupt */
  VICIntSelect &= ~0x10;
  /* Enable timer 0 interrupt */
  VICIntEnable = 0x10;
  /* Use slot 0 for timer 0 interrupt */
  VICVectCntl0 = 0x24;
  /* Set the address of ISR for slot 0 */
  VICVectAddr0 = (unsigned int)timer0ISR;

  /* Timer 1 interrupt is an IRQ interrupt */
  VICIntSelect &= ~0x20;
  /* Enable timer 1 interrupt */
  VICIntEnable = 0x20;
  /* Use slot 1 for timer 1 interrupt */
  VICVectCntl1 = 0x25;
  /* Set the address of ISR for slot 1 */
  VICVectAddr1 = (unsigned int)timer1ISR;

  /* Reset timer 0 */
  T0TCR = 0;
  /* Set the timer 0 prescale counter */
  T0PR = 2500;
  /* Set timer 0 match register */
  T0MR0 = 1000;
  /* Generate interrupt and reset counter on match */
  T0MCR = 3;
  /* Start timer 0 */
  T0TCR = 1;

  /* Reset timer 1 */
  T1TCR = 0;
  /* Set the timer 1 prescale counter */
  T1PR = 2500;
  /* Set timer 1 match register */
  T1MR0 = 1000;
  /* Generate interrupt and reset counter on match */
  T1MCR = 3;
  /* Start timer 1 */
  T1TCR = 1;

  /* Enable Interrupts */
  __ARMLIB_enableIRQ();

  while (timer0Count < 5 && timer1Count < 5);

  return 0; 
}
