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

#define BUTTON (1 << 29)
#define LED (1 << 2)

#define PIOB_ID 3

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

#define PROCESSOR_CLOCK_FREQUENCY 184320000
#define MCK_FREQUENCY (PROCESSOR_CLOCK_FREQUENCY / 4)

void
BoardInit(void)
{  
  /* Enable PIO clocks */
  PMC_PCER = 1 << PIOB_ID;
  /* Setup LEDs */
  PIOB_PER = LED;
  PIOB_OER = LED;
  PIOB_SODR = LED;
}

unsigned long
MCKFrequency(void)
{
  return MCK_FREQUENCY;
}

static CTL_ISR_FN_t userButtonISR;

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

void
SetButtonPressedISR(CTL_ISR_FN_t isr)
{
  userButtonISR = isr;

  // Setup PIO
  PIOB_ODR = BUTTON;
  PIOB_PER = BUTTON;
  PIOB_MDDR = ~BUTTON;
  PIOB_MDER = BUTTON;
  PIOB_IER = BUTTON;
  ctl_set_isr(PIOB_ID, 0, CTL_ISR_TRIGGER_LOW_LEVEL, buttonISR, 0);
  ctl_unmask_isr(PIOB_ID);
}

void
SetLeds(unsigned v)
{
  if (v)
    PIOB_CODR = LED;
  else
    PIOB_SODR = LED;
}
