// 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.
//
////////////////////////////////////////////////////////////////////////////////
//
//      Logic Product Development SDKLH75401-10 Timer Interrupt Example
//
// Description
// -----------
// This example demonstrates setting up interrupt handlers and timers.
//
////////////////////////////////////////////////////////////////////////////////

#include <targets/LH754xx.h>

#define TIMER0_INT 4
#define TIMER1_INT 5

static int timer0Count, timer1Count;

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

static void
timer0ISR(void)
{
  if (++timer0Count % 2)
    GPIO_PFDR &= ~2;
  else
    GPIO_PFDR |= 2;
  /* Clear the timer 0 interrupt */
  Timer0_STATUS = 1;
  /* Update VIC priorities */
  VIC_VectAddr = 0;
}

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

static
void
timer1ISR(void)
{
  if (++timer1Count % 2)
    GPIO_PFDR &= ~4;
  else
    GPIO_PFDR |= 4;
  /* Clear the timer 1 interrupt */
  Timer1_STATUS = 1;
  /* Update VIC priorities */
  VIC_VectAddr = 0;
}

int
main(void)
{
  /* Write "ldr pc, [pc, #-0xFF0]" instruction to IRQ exception vector */
  *(volatile unsigned long *)(0x00000018) = 0xE51FFFF0; 

  GPIO_PFDDR = 6;
  GPIO_PFDR = 6;

  /* Timer 0 interrupt is an IRQ interrupt */
  VIC_IntSelect &= ~(1 << TIMER0_INT);
  /* Enable timer 0 interrupt */
  VIC_IntEnable = 1 << TIMER0_INT;
  /* Use slot 0 for timer 0 interrupt */
  VIC_VectCtrl0 = 0x20 | TIMER0_INT;
  /* Set the address of ISR for slot 0 */
  VIC_VectAddr0 = (unsigned int)timer0ISR;

  /* Timer 1 interrupt is an IRQ interrupt */
  VIC_IntSelect &= ~(1 << TIMER1_INT);
  /* Enable timer 1 interrupt */
  VIC_IntEnable = 1 << TIMER1_INT;
  /* Use slot 1 for timer 1 interrupt */
  VIC_VectCtrl1 = 0x20 | TIMER1_INT;
  /* Set the address of ISR for slot 1 */
  VIC_VectAddr1 = (unsigned int)timer1ISR;

  /* Interrupt on timer 0 overflow */
  Timer0_INT_CTRL = 1;

  /* Set clock division to 128 */
  Timer0_CTRL = 0x18;

  /* Start timer 0 */
  Timer0_CTRL |= 2;

  /* Interrupt on timer 1 overflow */
  Timer1_INT_CTRL = 1;

  /* Set clock division to 2 */
  Timer1_CTRL = 0x0;

  /* Start timer 1 */
  Timer1_CTRL |= 2;

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

  return 0; 
}
