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

#define LED1 (1 << 1)
#define LED2 (1 << 4)
#define LED3 (1 << 2)
#define LEDS (LED1 | LED2 | LED3)

#define SW3 (1 << 12)
#define SW4 (1 << 5)
#define SW5 (1 << 9)

#define PIO_INT   8       /* Parallel I/O Controller A interrupt */

#define PROCESSOR_CLOCK_FREQUENCY 32768000

void
BoardInit(void)
{
  PIO_PER = LEDS | SW3 | SW4 | SW5;
  PIO_OER = LEDS;
}

unsigned long
TicksPerSecond(void)
{
  return 250;  
}

static CTL_ISR_FN_t userButtonISR;
static void
buttonISR(void)
{
  unsigned long isr = PIO_ISR;
  unsigned long pdsr = PIO_PDSR;
  userButtonISR();
}

void
SetButtonPressedISR(CTL_ISR_FN_t isr)
{
  userButtonISR = isr;
  // Setup PIO
  // LEDs SW1, SW2, SW3 and SW4 push buttons are debounced, buffered and connected to P12/FIQ, P9/IRQ0, P1/TIOA0 and P2/TIOB0, respectively.
  PIO_IER =  SW3 | SW4 | SW5;
  ctl_set_isr(PIO_INT, 0, CTL_ISR_TRIGGER_LOW_LEVEL, buttonISR, 0);
  ctl_unmask_isr(PIO_INT);
}

void
SetLeds(unsigned v)
{
  unsigned l  = 0;
  if (v & 1)
    l |= LED1;
  if (v & 2)
    l |= LED2;
  if (v & 4)
    l |= LED3;
  PIO_SODR = l;
  l = ~l & LEDS;
  PIO_CODR = l;
}
