/*****************************************************************************/
/* FILE NAME: main.c                            COPYRIGHT (c) Freescale 2010 */
/*                                                       All Rights Reserved */
/*																			 */
/* MPC5668 Example Projects Suite											 */
/* 1.0 System Clocks Examples												 */
/*																			 */
/* Revision History															 */
/* 		Rev: 1.0 		Author:	Steven McLaughlin  		DATE: 23/07/2010 	 */
/*																			 */
/* Example demostrates the main running system clocks of MPC5668 and the user*/
/* can toggle through them pressing PE0 and view the toggling LED on PE1 and */
/* attached a scope to CLKOUT on PK9 to view waveform						 */
/*****************************************************************************/
#include "mpc5668.h"

	uint32_t count; 
  
void PLLinit(void);
/********************************** main *************************************/
void main (void) 
{
	uint32_t sys_clk = 0;
	/*---------------------ENABLE CLKOUT-------------------------------------*/
	SIU.PCR[153].R = 0x060C; 					/* CLKOUT - PK9 */
	SIU.ECCR.B.ECDF = 0;     					/* CLKOUT = Set to 0 for sys freq. */
	SIU.ECCR.B.ECEN = 1; 						/* enable CLKOUT */

	/*-------------------LED and Switch port init-----------------------------*/
	SIU.PCR[64].R=0x0100;						/* IBE on PE0 - switch connection */
	SIU.PCR[65].R=0x0200;						/* OBE on PE1 - LED connection */

	
  while(1)
    {   
	if (SIU.GPDI[64].R == 1)                 	/* SW1 to select system clock on PE1 */
    {
        sys_clk=sys_clk++;
        if (sys_clk == 3)
			{ 
				sys_clk=0; 
			}
		}
		switch (sys_clk)
		{
			case(0):
				SIU.SYSCLK.B.SYSCLKSEL = 0x0; 		/* 16MHz IRC as system clock */
			break; 
		
			case(1):
				SIU.SYSCLK.B.SYSCLKSEL = 0x1; 		/* 40MHz external crystal as system clock */
			break;
		
			case(2):
				PLLinit();							/* 116MHz PLL from IRC */
			break;
		}

		for (count=0; count<100000; count++);		/* loops to toggle PE1 */
		SIU.GPDO[65].R = 0x01;
		for (count=0; count<100000; count++);
		SIU.GPDO[65].R = 0x00;
    }
 
}/* end of main() */

void PLLinit(void)
{  	
	int ERFD = 3;
	int EPREDIV = 9;
	int EMFD = 112;

	/* Select crystal as CLK Source */
	SIU.SYSCLK.B.SYSCLKSEL = 0x1;

	/* Configure PLL CTRL Regs */
	FMPLL.ESYNCR1.B.CLKCFG = 0x7;
	FMPLL.ESYNCR2.B.ERFD = ERFD+2;
	FMPLL.ESYNCR1.B.EPREDIV = EPREDIV;
	FMPLL.ESYNCR1.B.EMFD = EMFD;

	/* Wait for PLL to lock */ 
	while(FMPLL.SYNSR.B.LOCK != 1);

	/* Change pll up to final freq */
	FMPLL.ESYNCR2.B.ERFD = ERFD;

	/* Switch from IRC to PLL */ 
	SIU.SYSCLK.B.SYSCLKSEL = 0x2;
	SIU.ECCR.B.ECDF = 4;     		/* Must have CLKOUT/4 for full speed PLL (116MHz) */

} /* End of PLLinit */
 