/******************************************************************************/
/*  lpc_blink_switch_irq LPC2129                                              */
/*  LED Flasher - Timer Interrupt example for arm-elf-gcc                     */
/*  Lights LEDs on Startup and Flashs LEDs when Button1 is pressed.           */
/******************************************************************************/
/*  Inspired by a sample application from Keil Elektronik                     */
/*  A lot of information has been found in a sample from R O Software.        */
/******************************************************************************/
/*  Sample for WinARM by M.Thomas <eversmith@heizung-thomas.de>               */
/*  http://www.siwawi.arubi.uni-kl.de/avr_projects                            */
/******************************************************************************/

#include "lpc21xx_keil.h"
#include "config.h"


#include "VIClowlevel.h"

/*
This code will generate PWM

*/
#define LED2Y    23
#define LED2BITY (1<<LED2Y)
#define LED3Y    22
#define LED3BITY (1<<LED3Y)
extern int count10flag;
extern int count20flag;

static void systemInit(void)
{
	// --- enable and connect the PLL (Phase Locked Loop) ---
	// a. set multiplier and divider
	PLLCFG = MSEL | (1<<PSEL1) | (0<<PSEL0);
	// b. enable PLL
	PLLCON = (1<<PLLE);
	// c. feed sequence
	PLLFEED = PLL_FEED1;
	PLLFEED = PLL_FEED2;
	// d. wait for PLL lock (PLOCK bit is set if locked)
	while (!(PLLSTAT & (1<<PLOCK)));
	// e. connect (and enable) PLL
	PLLCON = (1<<PLLE) | (1<<PLLC);
	// f. feed sequence
	PLLFEED = PLL_FEED1;
	PLLFEED = PLL_FEED2;
	
	// --- setup and enable the MAM (Memory Accelerator Module) ---
	// a. start change by turning of the MAM (redundant)
	MAMCR = 0;	
	// b. set MAM-Fetch cycle to 3 cclk as recommended for >40MHz
	MAMTIM = MAM_FETCH;
	// c. enable MAM 
	MAMCR = MAM_MODE;

	// --- set VPB speed ---
	VPBDIV = 2;// VPBDIV_VAL;

    // --- map INT-vector ---
	#if defined(RAM_RUN)
	  MEMMAP = MEMMAP_USER_RAM_MODE;
	#elif defined(ROM_RUN)
	  MEMMAP = MEMMAP_USER_FLASH_MODE;
	#else
	#error RUN_MODE not defined!
	#endif
}

static void gpioInit(void)
{
   IODIR1 = 0x00FF0000;                      /* P1.16..23 defined as Outputs  */
}


int main(void) 
{
	
	systemInit();			// PLL, MAM etc.
	gpioInit(); 
	enableIRQ();
	init_PWM();
	
	while (1) {                               /* Loop forever */
	
	if (count10flag == 1)
	{
	    count10flag = 0;
		PWMMR0 = 4000;
		PWMMR4 = 500;
	    PWMLER = 0x7f;
		//PWMTCR = 0x09; // Counter Enable, PWM Mode Enabled(bit0, bit3)  
	}
	else if (count20flag == 1)
	{
	   count20flag = 0;
	   PWMMR0 = 4000;
	   PWMMR4 = 1500;
	   PWMLER = 0x7f;
	}
	;
  }
	
	
	return 0; /* never reached */
}


/*
if (!(IOPIN0 & (1 <<15)))
	{
	  PWMMR4 = 2000;//
	  PWMLER = 0x7F;
	  IOSET1 = (1<<22); // enable LED3
	}
*/    