// 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 TC0_ID 17

static CTL_ISR_FN_t userTimerISR;

unsigned long idleCount;

static int count;

static void
timerISR(void)
{
  userTimerISR();
  /* Clear the timer interrupt */
  TC0_SR;
}

void
SetTimerISR(CTL_ISR_FN_t isr)
{
  PMC_PCER = 1 << TC0_ID; /* Ensure T0 peripheral clock is running */
  TC0_CCR = TC0_CCR_CLKDIS_MASK;
  TC0_IDR = 0xFFFFFFFF;
  TC0_CMR = TC0_CMR_CPCTRG | 3; /* Timer clock 4 (/128) */
  TC0_RC = MCKFrequency() / 128 / TicksPerSecond();
  TC0_IER = TC0_IER_CPCS;
  TC0_CCR = TC0_CCR_CLKEN | TC0_CCR_SWTRG;
  userTimerISR = isr;
  ctl_set_isr(TC0_ID, 1, CTL_ISR_TRIGGER_LOW_LEVEL, timerISR, 0);
  ctl_unmask_isr(TC0_ID);
}

unsigned long
TicksPerSecond(void)
{
  return 1000;
}

void
Idle()
{
  ++idleCount;
}


