// 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.
////////////////////////////////////////////////////////////////////////////////
//
//                    Cogent CSB637 Interrupt Example
//
// Description
// -----------
// This example demonstrates a simple interrupt handler. When running, pressing
// the button causes the irq_handler to execute which toggles
// the LEDs.
//
////////////////////////////////////////////////////////////////////////////////

#include <targets/AT91RM9200.h>

// Interrupt definitions
#define AIC_SMR(n) (*(&AIC_SMR0 + n))
#define AIC_SVR(n) (*(&AIC_SVR0 + n))

#define AIC_SRCTYPE_INT_LEVEL_SENSITIVE 0x00    /* Level Sensitive */
#define AIC_SRCTYPE_INT_EDGE_TRIGGERED  0x20    /* Edge Triggered */
#define AIC_SRCTYPE_EXT_LOW_LEVEL       0x00    /* Low Level */
#define AIC_SRCTYPE_EXT_NEGATIVE_EDGE   0x20    /* Negative Edge */
#define AIC_SRCTYPE_EXT_HIGH_LEVEL      0x40    /* High Level */
#define AIC_SRCTYPE_EXT_POSITIVE_EDGE   0x60    /* Positive Edge */

#define BUTTON (1 << 29)

#define PIOB_ID 3

#define LED (1 << 2)

static void
ledInit(void)
{
  PIOB_PER = LED;
  PIOB_OER = LED;
  PIOB_SODR = LED;
}

static void
ledOn(void)
{
  PIOB_CODR = LED;
}

static void
ledOff(void)
{
  PIOB_SODR = LED;
}

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

void
piob_irq_handler(void)
{
  unsigned long isr = PIOB_ISR;
  unsigned long pdsr = PIOB_PDSR;
  if (isr & BUTTON)
    {
      if (pdsr & BUTTON)
        ledOff();
      else
        ledOn();
    }
  AIC_EOICR = 0;
}

int
main(void)
{
  ledInit();
  
  // Enable PIO clocks.
  PMC_PCER = 1 << PIOB_ID;

   // Set up PIO interrupt
  AIC_IDCR = 1 << PIOB_ID;
  AIC_SVR(PIOB_ID) = (unsigned)piob_irq_handler;
  AIC_SMR(PIOB_ID) = AIC_SRCTYPE_INT_LEVEL_SENSITIVE;
  AIC_ICCR = 1 << PIOB_ID;
  AIC_IECR = 1 << PIOB_ID;
  PIOB_ODR = BUTTON;
  PIOB_PER = BUTTON;
  PIOB_MDDR = ~BUTTON;
  PIOB_MDER = BUTTON;
  PIOB_IER = BUTTON;

   __ARMLIB_enableIRQ();

  while(1);

}
