// 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 LED_3 (1 << 3)
#define LED_4 (1 << 4)
#define LED_5 (1 << 5)
#define LED_6 (1 << 6)
#define LED_16 (1 << 16)
#define LED_17 (1 << 17)
#define LED_18 (1 << 18)
#define LED_19 (1 << 19)
#define LEDS (LED_3 | LED_4 | LED_5 | LED_6 | LED_16 | LED_17 | LED_18 | LED_19)

#define SW1 (1 << 12)
#define SW2 (1 << 9)
#define SW3 (1 << 1)
#define SW4 (1 << 2)

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

#define PROCESSOR_CLOCK_FREQUENCY 66000000

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

unsigned long
TicksPerSecond(void)
{
  return 503;
}

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 = SW1 | SW2 | SW3 | SW4;
  ctl_set_isr(PIO_INT, 0, CTL_ISR_TRIGGER_LOW_LEVEL, buttonISR, 0);
  ctl_unmask_isr(PIO_INT);
}

void
SetLeds(unsigned v)
{
  v = ((v & 0xF) << 3) | ((v & 0xF0) << 12);
  PIO_CODR = v;
  v = ~v & LEDS;
  PIO_SODR = v;
}
