
//------------------------------------------------------------------------------
// Copyright (c) 2012 by Silicon Laboratories. 
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Silicon Laboratories End User 
// License Agreement which accompanies this distribution, and is available at
// http://developer.silabs.com/legal/version/v10/License_Agreement_v10.htm
// Original content and implementation provided by Silicon Laboratories.
//------------------------------------------------------------------------------
// library
#include <si32McuComponent.h>
// hal
#include <si32_device.h>
#include <SI32_TIMER_A_Type.h>
// application
#include "myApplication.h"
#include "myTIMER0.h"

//------------------------------------------------------------------------------
void myTIMER0_initialize_memory()
{
  // nothing to do.
}

//------------------------------------------------------------------------------
void TIMER0L_IRQHandler(void)
{
  // nothing to do.
}

//------------------------------------------------------------------------------
void TIMER0H_IRQHandler(void)
{
  // nothing to do.
}

//------------------------------------------------------------------------------
void myTIMER0_enter_default_mode()
{
  // nothing to do
}

//------------------------------------------------------------------------------
void myTIMER0_enter_active_mode()
{
  // The codec is clocked externally from TIMER_EX_A on the UDP.
  // TIMER_EX_A is P1.11 on the MCU.
  SI32_TIMER_A_initialize(SI32_TIMER_0,
                          0x00000000,
                          0x00FF00FF,
                          0x00000000,
                          0x00000000);
  SI32_TIMER_A_select_split_timer_mode(SI32_TIMER_0);
  SI32_TIMER_A_select_square_wave_output_mode(SI32_TIMER_0);

  // Use timer0 to drive a square wave on P1.11 to feed MCLK on the codec.
  // SystemCoreClock = AHB; the USB oscillator at 48MHz.
  // APB = AHB / 1 by default; so its 48MHz.
  // MCLK has to be 256 * the sample rate.
  // To get started, target Fout = 48KHz.
  // 256 & 48000 = 12288000.
  SI32_TIMER_A_select_high_clock_source_apb_clock(SI32_TIMER_0);
  // Fout = (Ftimer / (65536 - HCCR)) / 2
  // 2 * Fout = Ftimer / (65536 - HCCR)
  // (65536 - HCCR) * 2 * Fout = Ftimer
  // 65536 - HCCR = Ftimer / 2 / Fout
  // HCCR = 65536 - (Ftimer / 2 / Fout)
  //uint32 hccr = 65536 - (SystemCoreClock / 12288000 / 2);  // its really 12 to drive the codec pll
  uint32 hccr = 65534;
  SI32_TIMER_A_set_high_count(SI32_TIMER_0, hccr);
  SI32_TIMER_A_set_high_reload(SI32_TIMER_0, hccr);
  SI32_TIMER_A_start_high_timer(SI32_TIMER_0);
}

//---eof------------------------------------------------------------------------
