// CrossWorks Tasking Library.
//
// CTL support for the ATMEL AT91SAM9263-EK evaluation board
//
// Copyright (c) 2007 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 <ctl_api.h>
#include <targets/AT91SAM9263.h>

#define LEDS (1<<8) // DS1
#define BUTTONS (1<<5) // BP1

void
ctl_board_init(void)
{
  PMC_PCER |= PMC_PCER_PIOB; // enable PIOB peripheral clock
  PIOB_PER = LEDS; // Set in PIO mode
  PIOB_OER = LEDS; // Configure in Output
}

static CTL_ISR_FN_t userButtonISR;
void
buttonISR(void)
{
  unsigned long isr = PIOC_ISR;
  unsigned long pdsr = PIOC_PDSR;
  userButtonISR();  
}

void 
ctl_board_on_button_pressed(CTL_ISR_FN_t buttonFn)
{
  userButtonISR = buttonFn;
  PMC_PCER |= PMC_PCER_PIOC_PIOD_PIOE; // enable PIOC peripheral clock  
  // Setup PIO
  PIOC_ODR = BUTTONS;
  PIOC_PER = BUTTONS;
  PIOC_MDDR = ~BUTTONS;
  PIOC_MDER = BUTTONS;
  PIOC_IER = BUTTONS;
  ctl_set_isr(4, 0, CTL_ISR_TRIGGER_LOW_LEVEL, buttonISR, 0);
  ctl_unmask_isr(4);
}

void
ctl_board_set_leds(unsigned v)
{
  if (v)
    PIOB_SODR = LEDS;
  else
    PIOB_CODR = LEDS;
}

void
delay(volatile unsigned int d)
{
  d *= 10;
  for (;d ;--d);
}

static CTL_ISR_FN_t timerFn;

static void
timerISR(void)
{
  timerFn();
  PIT_PIVR; // clear PITS
}

#define MCLK_KHz 99229 // 198.4578775/2 MHz

void
ctl_start_timer(CTL_ISR_FN_t t)
{
  timerFn = t;
  PIT_MR = ((MCLK_KHz/16)*10) | PIT_MR_PITEN | PIT_MR_PITIEN;
  PIT_PIVR; // clear PITS
#ifdef CTL_TASKING
  ctl_time_increment = 10; // so increment the counter by 10 to get the ms counter
#endif    
  ctl_set_isr(1, 1, CTL_ISR_TRIGGER_HIGH_LEVEL, timerISR, 0);
  ctl_unmask_isr(1);
}

unsigned long
ctl_get_ticks_per_second(void)
{
#ifdef CTL_TASKING
  return 1000;
#else
  return 100;
#endif
}


