/*******************************************************************************
* Freescale Semiconductor Inc.
* (c) Copyright 2011 Freescale Semiconductor, Inc.
* ALL RIGHTS RESERVED.
********************************************************************************
Services performed by FREESCALE in this matter are performed AS IS and without
any warranty. CUSTOMER retains the final decision relative to the total design
and functionality of the end product. FREESCALE neither guarantees nor will be
held liable by CUSTOMER for the success of this project.
FREESCALE DISCLAIMS ALL WARRANTIES, EXPRESSED, IMPLIED OR STATUTORY INCLUDING,
BUT NOT LIMITED TO, IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR
A PARTICULAR PURPOSE ON ANY HARDWARE, SOFTWARE ORE ADVISE SUPPLIED TO A PROJECT
BY FREESCALE, AND OR NAY PRODUCT RESULTING FROM FREESCALE SERVICES. IN NO EVENT
SHALL FREESCALE BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF
THIS AGREEMENT.
CUSTOMER agrees to hold FREESCALE harmless against any and all claims demands or
actions by anyone on account of any damage, or injury, whether commercial,
contractual, or tortuous, rising directly or indirectly as a result of an advise
or assistance supplied CUSTOMER in connection with product, services or goods
supplied under this Agreement.
********************************************************************************
* File main.c
* Owner b34874
* Version 1.0 // version 0.x is reserved for development phase and
// should not be placed in the repository
* Date August-05-2011
* Classification General Business Information/Internal Use Only/Confidential Proprietary
* Brief Brief description of the file
********************************************************************************
* Detailed Description:
* MCU goes after delay to STOP mode. After detection of edge on SCIO MCU wake-up and  
* after delay go back to STOP mode. Bus clock can visualize on pin PE4. 
* Tested on: PC9S12GN32 0N48A, TWR-S12GN32, 
* OSCCLK:8MHz; BUSCLK:16MHz
********************************************************************************
Revision History:
Version Date Author Description of Changes
1.0 May/11/2011 b34874 Initial Version
*******************************************************************************/
#include <hidef.h>      /* common defines and macros */
#include "derivative.h"      /* derivative-specific definitions */


volatile unsigned char sc0_data_in;

//==============================================================================
/*
• PLL Engaged External (PEE)
— The Bus Clock is based n the PLLCLK.
— 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).
*/
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 = 0B11000011;                   // bus=fPLL/2; Oscillator continues to run in Stop Mode; COP is clocked from OSCCLK
 if(CPMUCLKS != 0B11000011)               // 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.
  }
 //--------------------------------------
}

//==============================================================================

#pragma CODE_SEG NON_BANKED
interrupt 20 void SCI0_Isr(void)
{   
 unsigned char scicr2,scisr1;
 scisr1 = SCI0SR1;                          // save status register actual status
 scicr2 = SCI0CR2;                          // save control register actual status

SCI0SR2 = 0x80;  //Alternative Map
//if edge interrupt is enabled and corresponding interrupt flag is set
if((SCI0ACR1 & SCI0ACR1_RXEDGIE_MASK) && (SCI0ASR1 & SCI0ASR1_RXEDGIF_MASK)) 
  {
    SCI0ACR1 = 0x00; //Receive Input Active Edge Interrupt Disable - RXEDGIF interrupt requests disabled
    SCI0ASR1 = 0x80; //clear Receive Input Active Edge Interrupt Flag - RXEDGIF
    PTT_PTT4 = ~PTT_PTT4;           //just negate the LED
    SCI0SR2 = 0x00;  //Back from Alternative Map
  }
else
  {
   SCI0SR2 = 0x00;  //Back from Alternative Map 
   //if receiver interrupt is enabled and corresponding interrupt flag is set
   if((scicr2 & SCI0CR2_RIE_MASK) && ((scisr1 & (SCI0SR1_OR_MASK | SCI0SR1_RDRF_MASK))))
    {
      if(scisr1 & SCI0SR1_OR_MASK)            // if overrun error do nothing/something
        {
          (void)SCI0DRL;                      // clear interrupt flag 
          // do something
          PTT_PTT5 = ~PTT_PTT5;           //just negate the LED
        }
      else
        {
          sc0_data_in = SCI0DRL;             // read received character + clear interrupt flag                        
          PTT_PTT3 = ~PTT_PTT3;           //just negate the LED          
        }
    }
  }
}

#pragma CODE_SEG DEFAULT
    
//==============================================================================
void SCI0_Init(void)
{
   //----- BR = BUSCLK / (16*Baud rate) = 16000000 / (16*9600) = 104 = 0x68 -----      
   SCI0BDH = 0x00;  // prescaller value  
   SCI0BDL = 0x68;  // prescaller = 0x34 
   SCI0CR1 = 0x04;    
   SCI0CR2 = 0x24;  //receive enable, receive interrupt enable   
}
   
//==============================================================================
void Go_Stop(void)
{
   SCI0SR2 = 0x80;  //Alternative Map - The registers labelled SCIASR1 (0x0000),SCIACR1 (0x0001), SCIACR2 (0x00002) are accessible
   SCI0ACR1 = 0x80; //Receive Input Active Edge Interrupt Enable - RXEDGIF interrupt requests enabled  
   SCI0ASR1 = 0x80; //clear Receive Input Active Edge Interrupt Flag - RXEDGIF
   SCI0SR2 = 0x00;  //Back from Alternative Map
   asm STOP;        //Go to stop mode   
}
   
//==============================================================================





void main(void) {  

  
  unsigned int i,j;
  
  DDRT = 0x3C;          //PT2,PT3,PT4,PT5 as output for LED
  PTT = 0xFF;
  
  ECLKCTL_NECLK = 0;    //enable ECLK output (bus clock is visible on pin PB0 for TWR-S12G128, PS7 for TWR-S12GN32)
  
  SetPEEmodeBUSCLK(0x01, 0x80, 0x00);     // 16MHz BUSCLK from 8 MHZ oscclk, PEE mode            
  
  SCI0_Init();

  EnableInterrupts;

  asm ANDCC #0x7F;   //clear S bit = enable (pseudo) stop mode

  for(;;) {                
    
    PTT_PTT2 = 1;    //start delay loop
    
    //delay
    for(j=1;j<60;j++) 
      {
      for(i=1;i<60000;i++) asm nop;
      }
    PTT_PTT2 = 0;    //stop delay loop
    Go_Stop();       //go to STOP mode    
           
  } 

}
