/*
 * main implementation: use this 'C' sample to create your own application
 *
 */


#include "scg.h" /* include peripheral declarations S32K144 */
#include "ENET.h"




extern SCG_config_t configStruct;

eErrorCodes EnableIRQ (IRQn_Type irq)
{
	eErrorCodes ret = eNoError;

	/* Clear pending interrupt */
	S32_NVIC->ICPR[(irq >> 5)] |= 1 << (irq & 0x1F);
	/* Enable interrupt */
	S32_NVIC->ISER[(irq >> 5)] |= 1 << (irq & 0x1F);
	return ret;
}

void LPTMR_setup(void)
{
  PCC->PCCn[PCC_LPTMR0_INDEX] |= PCC_PCCn_CGC_MASK;  /* CGC=1: Clock enabled for LPTMR0 */
  LPTMR0->PSR |= //LPTMR_PSR_PBYP_MASK  |              /* PBYP=1: Prescaler/glitch filter is bypassed */
//                 LPTMR_PSR_PCS(1);                   /* PCS=1: Prescaler/glitch filter clock 1 (LPO1K_CLK) is selected */
                 LPTMR_PSR_PCS(0) | LPTMR_PSR_PRESCALE(0b0011);                   /* PCS=2: Prescaler/glitch filter clock 2 (RTC_CLK) is selected */
  LPTMR0->CMR = 0xFFFF;                                /* Trigger interrupt when CNR reached 500 (around 500ms) */
  LPTMR0->CSR |= LPTMR_CSR_TCF_MASK;                 /* Write 1 to clear TCF flag */
  LPTMR0->CSR |= LPTMR_CSR_TIE_MASK;                 /* TIE=1: Timer interrupt enabled */
  LPTMR0->CSR |= LPTMR_CSR_TEN_MASK;                 /* TEN=1: LPTMR is enabled */
  EnableIRQ(LPTMR0_IRQn);
}

void LPTMR0_IRQHandler(void)
{
  if( ( LPTMR0->CSR & LPTMR_CSR_TCF_MASK ) != 0 )
  {
    LPTMR0->CSR |= LPTMR_CSR_TCF_MASK;  /* Write 1 to clear TCF flag */
    ENET_dummy_tx();
  }
}

int main(void)
{
	uint32_t j;
	eErrorCodes ret;
	uint16_t data_val;
	volatile uint32_t coreFreq;

	/* Initialize SCG module */
	ret = SCG_init(&configStruct);
	if (eNoError != ret)
	{
		/* Error trap */
		while (1)
		{
			__asm("nop");
		}
	}
	/* Get core clock */
	coreFreq = SCG_get_clock_freq(eCoreClock);
	SCG_set_clock_freq(eSysPLL_div1,80000000);
	SCG_set_clock_freq(eSysOsc_div1,40000000);
	SCG_set_clock_freq(eFIRC_div1,MAXIMUM_AVAILABLE_FREQ);
	SCG_set_clock_freq(eSIRC_div2,MAXIMUM_AVAILABLE_FREQ);
	coreFreq = SCG_get_clock_freq(eFIRC_div1);
	coreFreq = SCG_get_clock_freq(eSIRC_div2);

/* Disable MPU to enable ENET DMA to access RAM */
	MPU->CESR = 0x00;


/* ENET initialization  */
	EnableIRQ(ENET_RX_IRQn);
	ENET_init(); /* configure ENET module */
	ENET_Rx_Init();

	LPTMR_setup();

	for(;;) {

	}
	return 0;
}
