// 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.
//
////////////////////////////////////////////////////////////////////////////////
//
//                ST STR71x Timer Interrupt Example
//
// Description
// -----------
// This example demonstrates an interrupt handler and setting up a timer.
//
////////////////////////////////////////////////////////////////////////////////

#include <targets/STR71x.h>

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

static int count;

#define IVECT 19
#define SIR(n) (*(&EIC_SIR0 + n))

#define LEDS (0xF << 11)

static void
ledOn()
{
  IOPORT2_PD |= LEDS;
}

static void
ledOff()
{
  IOPORT2_PD &= ~LEDS;
}

static void
ledInit()
{ 
  IOPORT2_PC0 |= LEDS;
  IOPORT2_PC1 &= ~LEDS;
  IOPORT2_PC2 |= LEDS;
  ledOff();
}

void
irq_handler(void)
{
  unsigned long ivr = EIC_IVR;
  if (count++ & 1)
    ledOff();
  else
    ledOn();
  TIM1_SR = ~TIM1_SR; /* Clear timer status register */
  EIC_IPR0 = 1 << EIC_CICR; /* EOI */
}

int
main(void)
{
  int i;

  ledInit();

  __ARMLIB_enableIRQ();
  EIC_ICR = 0; // Global IRQ output disabled
  EIC_IER0 = 0; // Disable interrupts
  EIC_IPR0 = 0xFFFFFFFF; // Clear all pending interrupts.

  EIC_IVR = 0;
  EIC_ICR = 1; // Global IRQ output enabled
  SIR(IVECT) =  1; // Set up priority
  EIC_IER0 = 1 << IVECT; // Enable interrupt channel

  TIM1_SR = 0; // Clear timer status register
  TIM1_CNTR = 0; // Reset the counter to 0xFFFC
  TIM1_CR2 = 32; // Set the prescaler
 
  TIM1_OCAR = 0xFFFF; // stop OCF1 being set when TOF is set
  TIM1_OCBR = 0xFFFF; // stop OCF2 being set when TOF is set

  TIM1_SR = 0; // Clear timer status register
  TIM1_CR2 |= 1 << 13; // Enable timer overflow interrupt
  TIM1_CR1 = 1 << 15; // Enable the timer

  while(count < 75);
    
  return 0; 
}
