// 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.
////////////////////////////////////////////////////////////////////////////////
//
//                   Atmel AT91SAM7A1-EK Interrupt Example
//
// Description
// -----------
// This example demonstrates a simple interrupt handler. When running, pressing
// the SW4/IRQ0 button causes the irq_handler to execute which toggles
// the LED.
//
////////////////////////////////////////////////////////////////////////////////

#include <targets/AT91SAM7A1.h>

// Interrupt definitions
#define GIC_SMR(n) (*(&GIC_SMR0 + n))
#define GIC_SVR(n) (*(&GIC_SVR0 + n))

#define GIC_SRCTYPE_INT_LEVEL_SENSITIVE 0x00    /* Level Sensitive */
#define GIC_SRCTYPE_INT_EDGE_TRIGGERED  0x20    /* Edge Triggered */
#define GIC_SRCTYPE_EXT_LOW_LEVEL       0x00    /* Low Level */
#define GIC_SRCTYPE_EXT_NEGATIVE_EDGE   0x20    /* Negative Edge */
#define GIC_SRCTYPE_EXT_HIGH_LEVEL      0x40    /* High Level */
#define GIC_SRCTYPE_EXT_POSITIVE_EDGE   0x60    /* Positive Edge */

#define IRQ0_INT 28

void irq0_handler(void) __attribute__ ((interrupt ("IRQ")));
void
irq0_handler(void)
{
  static int toggle;
  toggle ^= 1;
  if (toggle)
    GPT0C0_CODR = 0x00020000;
  else
    GPT0C0_SODR = 0x00020000;
  GIC_EOICR = 0;
}

void
ledInit()
{
  GPT0C0_ECR = 0x00000001;
  GPT0C0_PER = 0x00020000;
  GPT0C0_OER = 0x00020000;
  GPT0C0_CODR = 0x00020000;
}

int
main(void)
{
  // Put LDR PC, [PC, #-0xF20] instruction into IRQ vector in order to use 
  // hardware interrupt vectoring.
  *(volatile unsigned int *)0x00000018 = 0xE51FFF20;

  ledInit();

  __ARMLIB_enableIRQ();
  GIC_IDCR = 1 << IRQ0_INT;
  GIC_SVR(IRQ0_INT) = (unsigned)irq0_handler;
  GIC_SMR(IRQ0_INT) = GIC_SRCTYPE_EXT_POSITIVE_EDGE;
  GIC_ICCR = 1 << IRQ0_INT;
  GIC_IECR = 1 << IRQ0_INT;

  while(1);

}
