// Copyright (c) 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.

#include "test.h"
#include <ctl_api.h>
#include <targets/AT91SAM7.h>

#define PIOA_ID 2

#define SW1 (1 << 19)
#define SW2 (1 << 20)
#define SW3 (1 << 15)
#define SW4 (1 << 14)

void
BoardInit(void)
{  
  /* Enable PIO clocks */
  PMC_PCER = 1 << PIOA_ID; 
  /* Setup LEDs */
  PIOA_PER = 0x0000000F;
  PIOA_OER = 0x0000000F;
}

unsigned long
ProcessorClockFrequency(void)
{
  return 47923200;
}

static CTL_ISR_FN_t userButtonISR;
static void
buttonISR_IRQ0(void)
{
  userButtonISR();
}

static void
buttonISR_PIOB(void)
{
  unsigned long isr = PIOA_ISR;
  unsigned long pdsr = PIOA_PDSR;
  userButtonISR();
}

void
SetButtonPressedISR(CTL_ISR_FN_t isr)
{
  userButtonISR = isr;

  // Setup PIO
  PIOA_ODR = SW1 | SW2 | SW3 | SW4;
  PIOA_PER = SW1 | SW2 | SW3 | SW4;
  PIOA_MDDR = ~(SW1 | SW2 | SW3 | SW4);
  PIOA_MDER = SW1 | SW2 | SW3 | SW4;
  PIOA_IER = SW1 | SW2 | SW3 | SW4;
  ctl_set_isr(PIOA_ID, 0, CTL_ISR_TRIGGER_LOW_LEVEL, buttonISR_PIOB, 0);
  ctl_unmask_isr(PIOA_ID);
}

void
SetLeds(unsigned v)
{
  v &= 0xF;
  PIOA_CODR = v;
  v = ~v & 0xF;
  PIOA_SODR = v;
}
