#include <hidef.h>      /* common defines and macros */
#include "derivative.h"      /* derivative-specific definitions */


//==============================================================================
/*
• PLL Engaged External (PEE)
— The Bus Clock is based n the PLLCLK. Source is external oscillator.
— This mode can be entered from default mode PEI by performing the following steps:
– Configure the PLL for desired bus frequency.
– Program the reference divider (REFDIV[3:0] bits) to divide down oscillator frequency if
necessary.
– Enable the external oscillator (OSCE bit)
– Wait for oscillator to start up (UPOSC=1) and PLL to lock (LOCK=1).
BUSCLK = (OSCCLK/(REFDIV+1))*(SYNDIV+1)*2*1/2 = (OSCCLK*(SYNDIV+1))/(REFDIV+1)
- keep 
*/
void SetPEEmodeBUSCLK(byte _synr, byte _refdv, byte _postdiv)
{
 CPMUSYNR    = _synr;
 CPMUREFDIV  = _refdv;
 CPMUPOSTDIV = _postdiv;   
  
 CPMUOSC_OSCE = 1; //enable external oscillator OSCE
    
 while(!CPMUFLG_UPOSC)
  {// you can check for timeot here with error message report
  };    
 while(!CPMUFLG_LOCK)
  {// you can check for timeot here with error message report
  };    
 
  //--- select clocks --------------------
 CPMUCLKS = 0B10000011;                   // bus=fPLL/2; COP is clocked from OSCCLK
 if(CPMUCLKS != 0B10000011)               // After writing CPMUCLKS register, it is strongly recommended to read  
  {                                       // back CPMUCLKS register to make sure that write of PLLSEL,
     asm nop;                             // RTIOSCSEL, COPOSCSEL0 and COPOSCSEL1 was successful.
  }
 //--------------------------------------
}
//==============================================================================


void main(void) {
  
  ECLKCTL_NECLK = 0;                      // enable ECLK output (bus clock is visible on pin PB0 for TWR-S12G128, PS7 for TWR-S12GN32)
                                          // default clock setup after reset is PEI mode 6.25MHz BUSCLK
  
  /* put your own code here */
  //--- PLL Initialization ---------------
  //SetPEEmodeBUSCLK(0x58, 0x03, 0x00);   // 25MHz BUSCLK from 4 MHZ oscclk, PEE mode
  //SetPEEmodeBUSCLK(0x58, 0x07, 0x00);   // 25MHz BUSCLK from 8 MHZ oscclk, PEE mode
  //SetPEEmodeBUSCLK(0x03, 0x40, 0x00);   // 16MHz BUSCLK from 4 MHZ oscclk, PEE mode
  //SetPEEmodeBUSCLK(0x01, 0x80, 0x00);   // 16MHz BUSCLK from 8 MHZ oscclk, PEE mode
  //SetPEEmodeBUSCLK(0x01, 0x80, 0x07);   // 2MHz BUSCLK from 8 MHZ oscclk, PEE mode
  SetPEEmodeBUSCLK(0x02, 0x80, 0x00);     // 24MHz BUSCLK from 8 MHZ oscclk, PEE mode


	EnableInterrupts;


  for(;;) {
    _FEED_COP(); /* feeds the dog */
  } /* loop forever */
  /* please make sure that you never leave main */
}
