/******************************************************************************
						            Copyright (c) Freescale 2011

File Name :        $RCSfile: main.c,v $

Current Revision : $Revision: 1.0 $

PURPOSE:           main program entry.                       
                                                                          
                                                                       
DESCRIPTION:  function main() providing initial program entry.
                                                                          
UPDATE HISTORY                                                            
REV  AUTHOR    DATE        DESCRIPTION OF CHANGE                          
---  ------    --------    ---------------------                          
1.0  r28318    01/10/09    - initial coding
2.0  b30269    17/11/10    - Migrated to S12XHY, CRG_8MHz function was added for clock
                             setup
3.0  b30269    02/07/11    - Migrated to S12G64  

                                                                         
******************************************************************************/
/*===========================================================================*/
/* Freescale reserves the right to make changes without further notice to any*/
/* product herein to improve reliability, function, or design. Freescale does*/
/* not assume any  liability arising  out  of the  application or use of any */
/* product,  circuit, or software described herein;  neither  does it convey */
/* any license under its patent rights  nor the  rights of others.  Freescale*/
/* products are not designed, intended,  or authorized for use as components */
/* in  systems  intended  for  surgical  implant  into  the  body, or  other */
/* applications intended to support life, or  for any  other application  in */
/* which the failure of the Freescale product  could create a situation where*/
/* personal injury or death may occur. Should Buyer purchase or use Freescale*/
/* products for any such intended  or unauthorized  application, Buyer shall */
/* indemnify and  hold  Freescale  and its officers, employees, subsidiaries,*/
/* affiliates,  and distributors harmless against all claims costs, damages, */
/* and expenses, and reasonable  attorney  fees arising  out of, directly or */
/* indirectly,  any claim of personal injury  or death  associated with such */
/* unintended or unauthorized use, even if such claim alleges that  Freescale*/
/* was negligent regarding the  design  or manufacture of the part. Freescale*/
/* and the Freescale logo* are registered trademarks of Freescale Ltd.       */
/*****************************************************************************/

/************************* Include Files *************************************/
/* General Includes */
#include "derivative.h"
#include "target.h" 
#include <hidef.h>           /* also includes boolean definitions in stdtypes.h     */

/* Peripherals */
#include "S12_COMMON.h"
#include "S12SCIV5.h"				 /* SCI */

/************************* typedefs ******************************************/

/************************* #defines ******************************************/
/* PORT LOGIC defines */
#define OUTPUT         1
#define INPUT          0
#define ENABLE         1

#define HIGH_NIBBLE_MSK 0xF0
#define SW1_MSK         0xE0         
#define SW2_MSK         0xD0

/************************* Constants *****************************************/

/************************* Global Variables **********************************/

/************************* function prototypes *******************************/

/************************* Functions *****************************************/
#pragma CODE_SEG DEFAULT

/******************************************************************************
Function Name  : CPMU_Init
Engineer       : b30269	
Date           : 02/07/11
Parameters     : NONE
Returns        : NONE
Notes          : CPMU configuration to run at 25MHz bus clk.                               
******************************************************************************/
void CPMU_Init(void)
{
   /* 
      Initialise the system clock for Normal mode: 
      - 50MHz VCO, 50MHz PLL, 25MHz Bus CLK, from 8MHz Crystal 
   */
	
   CPMUSYNR    = 0x58;     /* VCOFRQ -> 48MHz < fVCO<= 50MHz SYNDIV = 24  */

   CPMUREFDIV  = 0x07;     /* REFDIV =  7                                 */     

   CPMUPOSTDIV = 0x00;     /* POSTDIV = 0, FBus 0 FPLL/2                  */

   while(!CPMUFLG_LOCK)
   {
      ;                /* 
                          Wait for VCO to stabilize, if failure occurs 
                          WD will be triggered
                       */
   }			 
 
   CPMUCLKS_PLLSEL = 1;  /* Switch clk to use PLL */
}

/******************************************************************************
Function Name  : PT1AD_PORT_Delay
Engineer       : b30269	
Date           : 02/07/11
Parameters     : NONE
Returns        : NONE
Notes          : Delay time required after reset, so signals at port are stable.                               
******************************************************************************/
void PT1AD_PORT_Delay(void)
{
    uint dummy_ctr;
    
    for(dummy_ctr=0; dummy_ctr<0x007f;dummy_ctr++)
    {
      ;
    }
}


/******************************************************************************
Function Name  : main
Engineer       : r28318	
Date           : 09/06/09
Parameters     : NONE
Returns        : NONE
Notes          : main routine called by Startup.c. 
******************************************************************************/
void main(void) 
{
 
   unsigned int ContinuousResult, x, y;
	 
	 CPMU_Init();
	 
   /* Configure AD7 "PAD15" port as outputs to drive MAX3387 FORCEOFF pin */        
   DDR0AD_DDR0AD7 = OUTPUT;
   /* Disable all AD port interrupts */
   PIE01AD        = 0x0000;                              
   /* Enable MAX3387 FORCEOFF = 1   */   
   PT0AD_PT0AD7   = ENABLE;
   
   /* Set baud rate 9600 => 0xA3 @ buss clock = 25 MHz                          */   
   SCI0BD    = 0x00A3;   /* SCI0BD = BusCLK/[16*9600]                           */
   SCI0CR2  |= 0x08;     /* Enable Tx for SCI0, signal at PIN 53 of 64 pin LQFP */
   
   LF;
   DisplayString("S12G64_ADC_DEMO Running");
   LF;

   /* LED1 driver configuration                  */ 
   PTP_PTP0  = 0x01;     /* Initialise PORT P 0 High; turn off LED */
   DDRP      = 0x01;     /* PORTR 0 as output                      */

   PER1AD    = 0xF4;     /* Enable pullups on Switches 1-4, and Transceiver Force Off */
   ATDDIENL  = 0xF0;

   
   PT1AD_PORT_Delay();  /* Give soome time to SWx signal is stable after reset        */
   
   
   /*** Select ATD opion via Reset & Switches ****/
   /*                                            */
   /* Default     = Single 10-Bit Conversion     */
   /* Reset + SW1 = 10-Bit Automatic Compare     */
   /* Reset + SW2 = Continuous 8-Bit Conversions */
   /**********************************************/
  
   switch (PT1AD & HIGH_NIBBLE_MSK)
   {
         
   case SW1_MSK: /* Reset + SW1 10-Bit Automatic Compare */
   
      DisplayString("10-Bit Automatic Compare, greater than 0x01FF");
      LF;
      DisplayString("LED1 starts toggling if RV1 conversion is greater than 0x01FF");
      LF;
     
      /* 10-Bit Automatic Compare */
      /* Initialize ADC           */
                   
      ATDCTL1  = 0x2F;    /* 10-Bit resolution */              

      ATDCTL3  = 0x90;    /* Right Justified Data, two conversions / sequence                */              

      ATDCTL4  = 0x01;    /* 6.25 MHz, Notice: 8MHz Max ATD Clock, Fatdlk = FBUS/(2*(PRS+1)) */
                          /* 6 ATD Clock cycles sample time                                  */              

      ATDDR0   = 0x01FF;  /* Comparison value 50% of VDD */

      ATDCMPHT = 0x0001;  /* Compare higher than on conversion AN10 */

      ATDCMPE  = 0x0001;  /* Enable comparisons for conversion AN10 */

      ATDCTL5  = 0x2A;    /* Start Continuous Conversions on PAD10  */              

      for(;;)
      {
         while (!ATDSTAT0_SCF);     /* wait for conversion sequence to complete          */
         ContinuousResult = ATDDR1; /* store AN10 conversion result to avoid overwriting */
         if (ATDSTAT2_CCF0)         /* Test to see if comparison is true                 */
           {
             PTP_PTP0 ^= 1;         /* Toggle LED1 */
           }
         else
           {
             PTP_PTP0 = 1; /* Turn off LED1 */
           }
           
         DisplayString("RV1 at AN10 Conversion = 0x");
         DisplayByte((unsigned char)(ContinuousResult>>8));
         DisplayByte((unsigned char)ContinuousResult);
         LF;

         /* Wait to display conversion result */
         for (x=0; x<2000; x++)
         {	
           for (y=0; y<500; y++)
           {} 
         }
         ATDSTAT0_SCF = 1; /* Clear Sequence Complete Flag   */
         ATDSTAT2_CCF0= 1; /* Clear Conversion Complete Flag */
      }
   
/*     This example performs two conversions per sequence, AN10 and AN11 on the same pin PAD10. 
       AN10 is used for the automatic compare. AN11 is written to the terminal window. With 
       automatic compare enabled for AN10, the ATDDR0 register is used to store the compare 
       value, the result will not be stored there at the end of conversion, but it is lost. AN10 
       is written to the terminal window to give an indication of the value of AN10. 
       In an ideal environment with no noise AN10=AN11, however as there will be some noise present 
       it is possible for AN10 and AN11 to differ slightly. When AN10 and AN11 approach the compare 
       value stored in ATDDR0, differences between them may give the appearance that the automatic 
       compare feature is behaving erroneously 
*/

   break;

  
   case SW2_MSK: /* Reset + SW2 Continuous 8-Bit Conversions */
                 
      DisplayString("8-Bit Continuous Conversion");
      LF;

      /* Continuous 8-Bit Conversion */
      /* Initialize ADC              */
                   
      ATDCTL1 = 0x0F;  /* 8-Bit resolution                                 */              

      ATDCTL3 = 0x88;  /* Right Justified Data, Single conversion sequence */              

      ATDCTL4 = 0x01;  /* 6.25 MHz, Notice: 8MHz Max ATD Clock, Fatdlk = FBUS/(2*(PRS+1)) */
                       /*   6 ATD Clock cycles sample time                                */              

      ATDCTL5 = 0x2A;  /* Start Continuous Conversions on PAD10 */              

      for(;;)
      {
         while (!ATDSTAT0_SCF);       /* wait for conversion sequence to complete         */
         ContinuousResult = ATDDR0;   /* store result in variable to avoid overwriting    */
         ATDSTAT0_SCF = 1;            /* Clear Sequence Complete Flag for next conversion */
         DisplayString("RV1 at AN10 Conversion = 0x");
         DisplayByte((unsigned char)(ContinuousResult>>8));
         DisplayByte((unsigned char)ContinuousResult);
         LF;
         
         /* Wait to display conversion result */
         for (x=0; x<2000; x++)
         {	
            for (y=0; y<500; y++)
            {
               ;
            } 
         }
      }
   
   break;



   default: /* Reset Single 10-Bit Conversion */


      DisplayString("10-Bit Single Conversion");    
      LF;
      DisplayString("Change RV1 value and press SW4 to perform another convertion");    
      LF;
      /* Single 10-Bit Conversion */
      /* Initialize ADC           */
                   
      ATDCTL1 = 0x2F;  /* 10-Bit resolution                                */              

      ATDCTL3 = 0x88;  /* Right Justified Data, Single conversion sequence */              

      ATDCTL4 = 0x01;  /* 6.25 MHz, Notice: 8MHz Max ATD Clock, Fatdlk = FBUS/(2*(PRS+1)) */ 
                       /* 6 ATD Clock cycles sample time                                  */             

      ATDCTL5 = 0x0A;  /* Start Single Conversion on PAD10                                */              

      for(;;)
      {
         while (!ATDSTAT0_SCF);  /* wait for conversion sequence to complete              */                 
         DisplayString("RV1 at AN10 Conversion = 0x");
         DisplayByte((unsigned char)(ATDDR0>>8));
         DisplayByte((unsigned char)ATDDR0);
         LF;
         
         /* Wait to debounce SW4 */
         for (x=0; x<2000; x++)
         {	
            for (y=0; y<500; y++)
            {
               ;
            }
         }
         
         while (PT1AD_PT1AD7)
         {
          ;
         } /* Wait for SW4 before starting next conversion                                */
         ATDCTL5 = 0x0A;    /* Start Single Conversion on AN10; simultaneously clears SCF */              
         
      } 
   
   }

}


