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

#define PERIOD 50  //50us

//==============================================================================
//SetPEEmodeBUSCLK
//==============================================================================
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.
  }
 //--------------------------------------
}

//==============================================================================
//TC0_ISR
//==============================================================================
#pragma CODE_SEG NON_BANKED
interrupt 8 void TC0_ISR(void)
{  
  TFLG1 = 0x01;             //clear the flag
  PTT_PTT7 = ~PTT_PTT7;     //toggle PT7
  TC0 = TC0 + PERIOD;    
}
#pragma CODE_SEG DEFAULT


//==============================================================================
//Timer_Init
//==============================================================================
void Timer_Init(void)
{  
  //timer clk = bus clk / prescaler = 16Mhz / 16 = 1MHz      
  TIOS = 0x01;    //channel 0 as output compare
  TIE = 0x01;     //interrupt enable  
  TSCR2 = 0x04;   //prescaler = 16
  TC0 = PERIOD;
  TSCR1 = 0xA0;   //timer enabled
}


void main(void) {
  /* put your own code here */
  
  ECLKCTL_NECLK = 0;                      // enable ECLK output (bus clock is visible on pin PB0 for TWR-S12G128/G240, PS7 for TWR-S12GN32/G64)
                                          // default clock setup after reset is PEI mode 6.25MHz BUSCLK
  SetPEEmodeBUSCLK(0x01, 0x80, 0x00);     // 16MHz BUSCLK from 8 MHZ oscclk, PEE mode
  
  DDRT = 0xF0;    //LEDs output  
  
  Timer_Init();
  
  EnableInterrupts;  


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