// 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/AT91M55800A.h>

#define PIOBIRQ_INT 14
#define IRQ0_INT 29

#define SW1 (1 << 20)
#define SW2 (1 << 9)
#define SW3 (1 << 17)
#define SW4 (1 << 19)

void
BoardInit(void)
{  
  /* Enable PIO clocks */
  APMC_PCER = 0x6000; 
  /* Setup LEDs */
  PIOB_PER |= 0x0000FF00;
  PIOB_OER |= 0x0000FF00;
  PIOB_SODR |= 0x0000FF00;
}

unsigned long
ProcessorClockFrequency(void)
{
  return 32000000;
}

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

static void
buttonISR_PIOB(void)
{
  unsigned long isr = PIOB_ISR;
  unsigned long pdsr = PIOB_PDSR;
  userButtonISR();
}

void
SetButtonPressedISR(CTL_ISR_FN_t isr)
{
  userButtonISR = isr;

  // Setup PIO
  PIOA_PDR = SW2;
  ctl_set_isr(IRQ0_INT, 0, CTL_ISR_TRIGGER_NEGATIVE_EDGE, buttonISR_IRQ0, 0);
  ctl_unmask_isr(IRQ0_INT);

  PIOB_ODR = SW1 | SW3 | SW4;
  PIOB_PER = SW1 | SW3 | SW4;
  PIOB_MDDR = ~(SW1 | SW3 | SW4);
  PIOB_MDER = SW1 | SW3 | SW4;
  PIOB_IER = SW1 | SW3 | SW4;
  ctl_set_isr(PIOBIRQ_INT, 0, CTL_ISR_TRIGGER_LOW_LEVEL, buttonISR_PIOB, 0);
  ctl_unmask_isr(PIOBIRQ_INT);
}

void
SetLeds(unsigned v)
{
  v <<= 8;
  PIOB_CODR = v;
  v = ~v & 0x0000FF00;
  PIOB_SODR = v;
}
