#include <csl_sar.h>
#include <csl_intc.h>
#include <csl_general.h>
#include <stdio.h>

#include "csl_gpt.h"
#include "csl_uart.h"
#include "csl_uartAux.h"
#include "csl_sysctrl.h"

#include "declarations.h"
#include "all_functions.h"
#include "math.h"
#include "hwafft.h"

Int32 *data=data_buf;
//#include "data_types.h"



/*----------------------------------------------Variables-----------------------------------------------------------------------*/



char *result;
int i=0,j=0,count=0,count_int=0,flag=0;
/*===================================================================================================================================================*/


extern void VECSTART(void);
Int16 CSL_gptIntrTest(void);
Int16 CSL_gptIntrTest_t1(void);
Uint32 getSysClk(void);


/*----------------------------------------------Variables-----------------------------------------------------------------------*/
Uint32    cpuCycleCount = 0;
Uint32    sysClk;
volatile Uint16    hitIsr = 0;
CSL_Handle    hGpt;


/*===============================================================================================================================================================*/
interrupt void gpt0Isr(void)
{

        /* Clear Timer Interrupt Aggregation Flag Register (TIAFR) */
        CSL_SYSCTRL_REGS->TIAFR = 0x01;
        USBSTK5515_ULED_toggle(3);
        //USBSTK5515_ULED_on(4);
        /*USBSTK5515_ULED_off(3);
        USBSTK5515_waitusec(1);
        USBSTK5515_ULED_on(3);
        USBSTK5515_waitusec(1);*/
        /*for(i=0;msg[i]!='\0';i++)
        {
                while((UART_LSR & 0x60)==0);  // Wait for TX ready
                EVM5515_UART_putChar(msg[i]);    // Write 1 byte

        }*/

        //Send_data(adc_single_data);

        int_adc_out_ch3[i]=Read_GPAIN1_CH3();

        i++;
        // For 100 times
        if(i == 2048)
        {
                IRQ_disable(TINT_EVENT);
                hitIsr = TRUE;
                flag=1;
        }
        /*count_int++;
        printf("\nvalue of count= %d\n",count_int);
        printf("\nvalue of ADC= %d\n",int_adc_out[i]);*/
        //IRQ_clear(TINT_EVENT);
}
/*===============================================================================================================================================================*/
/**
 *  \brief  GPT Interrupt Service Routine
 *
 *  \param  none
 *
 *  \return none
 */
interrupt void gpt1Isr(void)
{

        /* Clear Timer Interrupt Aggregation Flag Register (TIAFR) */
        CSL_SYSCTRL_REGS->TIAFR = 0x02;
        USBSTK5515_ULED_toggle(0);
        int_adc_out_ch5[j++]=Read_GPAIN1_CH5();

        // For 100 times
        if(j == 2048)
        {
                IRQ_disable(TINT_EVENT);
                hitIsr = TRUE;
                flag=1;
        }
        /*count_int++;
        printf("\nvalue of count= %d\n",count_int);
        printf("\nvalue of ADC= %d\n",int_adc_out[i]);*/
        //IRQ_clear(TINT_EVENT);
}



/*===================================================================================================================================================*/
int main(void)
{
        Int32 i;
        Int32 status;

        Int32 max_index_adc_ch5=0,small_index1=0,index1=0,zero_index1=0,Flag_index1=0;
        Int16 _1st_cycle,_2nd_cycle,_3rd_cycle,_4th_cycle,_5th_cycle,_6th_cycle;
        Int16 _1st_cycle1,_2nd_cycle1,_3rd_cycle1,_4th_cycle1,_5th_cycle1,_6th_cycle1;
        Int16 ind_cnt1[100];
        Int16 ind_cnt[100];

        Int32 max_index_adc=0,small_index=0,index=0,zero_index=0,Flag_index=0;

        SYS_PCGCR1=0; //INIT clock
        SYS_PCGCR2=0; //INIT clock
        SYS_EXBUSSEL = 0x0A00;  // Enable user LEDs on external bus

            //USBSTK5515_GPIO_setDirection( 18, GPIO_OUT );
            USBSTK5515_ULED_init();
       *(ioport volatile unsigned *)0x0001 = 0x000E;
        asm(" idle"); // must add at least one blank before idle in " ".//HWAFFT init


      //  My_UART(); //uart initialization and setup for 19200 at 60MHz

        Init_SAR_ch3(); //ADC init
        Delay(100);

        for(i=0;i<DATA_LEN_2048;i++)
        {
            int_adc_out_ch3[i]=0;

        }
        status=CSL_gptIntrTest();
        if(CSL_TEST_PASSED == status)
                   printf("\nCSL SAR Interrupt Mode Test Passed\n");
                else
                   printf("\nCSL SAR Interrupt Mode Test Failed\n");

        max_index_adc=find_high_index(int_adc_out_ch3, DATA_LEN_2048);
        printf("\nMax index at ch3= %d", max_index_adc);
        printf("\n the max amplitude on channel 3= %d",int_adc_out_ch3[max_index_adc]);

        for(i=0;i<DATA_LEN_2048;i++)
               {
                    if(int_adc_out_ch3[i]==int_adc_out_ch3[max_index_adc])
                    {
                        ind_cnt[i]=i;
                    }
                }

        Init_SAR_ch5(); //ADC init
        for(i=0;i<DATA_LEN_2048;i++)
        {
           int_adc_out_ch5[i]=0;

        }

            status=CSL_gptIntrTest_t1();


        max_index_adc_ch5=find_high_index(int_adc_out_ch5, DATA_LEN_2048);
        printf("\nMax index at ch5= %d", max_index_adc_ch5);
        printf("\n the max amplitude on channel 5= %d",int_adc_out_ch5[max_index_adc_ch5]);

        for(i=0;i<DATA_LEN_2048;i++)
       {
            if(int_adc_out_ch5[i]==int_adc_out_ch5[max_index_adc_ch5])
            {
                ind_cnt1[i]=i;

            }
        }

        if(CSL_TEST_PASSED == status)
           printf("\nCSL SAR Interrupt Mode Test Passed\n");
        else
           printf("\nCSL SAR Interrupt Mode Test Failed\n");


        for(i=0;i<DATA_LEN_1024;i++)
            data[i]=int_adc_out_ch3[i];



        phase_angle = FFT_ch3(&data[0]); //1024 fft calculation for samples from adc ch3

        for(i=0;i<DATA_LEN_1024;i++)
            data[i]=int_adc_out_ch5[i];
        phase_angle_ch5 = FFT_ch5(&data[0]); //1024 fft calculation for samples from adc ch3

        angle_diff=Phase_diff(phase_angle_ch5, phase_angle);

        printf("\n Phase Difference= %f ",angle_diff);



        while(1);

}

/*===============================================================================================================================================================*/
Int16 CSL_gptIntrTest(void)
{

        CSL_Status    status;
        CSL_Config    hwConfig;
        CSL_GptObj    gptObj;
        Uint32        cpuCycleDelta;

        hitIsr   = FALSE;
        status   = 0;

        // Get the System clock value at which CPU is currently running
        /*sysClk = getSysClk();

        // CPU clock cycles that  are 1% of the sysClk" value
        cpuCycleDelta = (sysClk/100);

        printf("\n\nCPU clock is running at %ldKHz\n", sysClk);
        printf("Timer Prescaler Divide Value is Set to Divide by 4\n");
        printf("GPT Runs at Rate 1/4 of the CPU System Clock\n");
        printf("GPT Count is Initialized to 1/4 of CPU Clock Cycles per Millisecond\n");
        printf("With Reference to CPU Clock GPT Will Take 1 Millisecond to Count Down the Timer to 0\n");
        printf("So The CPU Should Execute Approximately %ld(±1%%) Clock Cycles ",sysClk);
        printf("From the Starting of the Timer Till the Expiry of the Timer\n\n");*/

        /* Open the CSL GPT module */
        hGpt = GPT_open (GPT_0, &gptObj, &status);
        if((NULL == hGpt) || (CSL_SOK != status))
        {
                printf("GPT Open Failed\n");
                return (CSL_TEST_FAILED);
        }
        else
        {
                printf("GPT Open Successful\n");
        }

        /* Reset the GPT module */
        status = GPT_reset(hGpt);
        if(CSL_SOK != status)
        {
                printf("GPT Reset Failed\n");
                return (CSL_TEST_FAILED);
        }
        else
        {
                printf("GPT Reset Successful\n");
        }

        /* Clear any pending interrupts */
        IRQ_clearAll();

        /* Disable all the interrupts */
        IRQ_disableAll();

        IRQ_setVecs((Uint32)(&VECSTART));
        IRQ_plug(TINT_EVENT, &gpt0Isr);
        IRQ_enable(TINT_EVENT);

        hwConfig.autoLoad    = GPT_AUTO_ENABLE;
        hwConfig.ctrlTim     = GPT_TIMER_ENABLE;
        hwConfig.preScaleDiv = GPT_PRE_SC_DIV_1;
        //for 1ms


        hwConfig.prdLow    = 0x00F4; //1us
        hwConfig.prdHigh   = 0x0000;


        /* Configure the GPT module */
        status =  GPT_config(hGpt, &hwConfig);
        if(CSL_SOK != status)
        {
                printf("GPT Config Failed\n");
                return (CSL_TEST_FAILED);
        }
        else
        {
                printf("GPT Config Successful\n");
        }

        /* Enable CPU Interrupts */
        IRQ_globalEnable();

        /* Start the Timer */
        GPT_start(hGpt);

        /* Wait for the timer interrupt */
        /* This loop takes 12 CPU cycles to execute on iteration.
        So the CPU cycles executed after starting the timer till the
        expiry of the timer will be 12*cpuCycleCount. */
        while(hitIsr != TRUE)
        {
                cpuCycleCount++;
        }

        /* Disable the CPU interrupts */
        IRQ_globalDisable();

        /* Clear any pending interrupts */
        IRQ_clearAll();

        /* Disable all the interrupts */
        IRQ_disableAll();

        /* Stop the Timer */
        status = GPT_stop(hGpt);
        if(CSL_SOK != status)
        {
                printf("GPT Stop Failed \n");
                return (CSL_TEST_FAILED);
        }
        else
        {
                printf("GPT Stop Successful\n");
        }

        status = GPT_reset(hGpt);

        /* Display the number of CPU cycles executed */
        printf("\nTimer Count Reached Zero\n");
        cpuCycleCount *= 12;
        printf("\n\nNUMBER OF CPU CYCLES EXECUTED AFTER STARTING THE TIMER TILL THE TIMER EXPIRY: ");
        printf("%ld\n", cpuCycleCount);

        /* Test passes if the "cpuCycles" value is in the range
        ((sysClk) ± (1% of sysClk)) */
        if(((cpuCycleCount - cpuCycleDelta) < sysClk) &&
        ((cpuCycleCount + cpuCycleDelta) > sysClk))
        {
                printf("GPT IS RUNNING AT THE CONFIGURED RATE!\n\n");
        }
        else
        {
                printf("GPT IS NOT RUNNING AT THE CONFIGURED RATE!\n\n");
                return (CSL_TEST_FAILED);
        }

        /* Close The GPT Module */
        status = GPT_close(hGpt);
        if(CSL_SOK != status)
        {
                printf("GPT Close Failed\n");
                return (CSL_TEST_FAILED);
        }

        return (CSL_TEST_PASSED);
}
/*===============================================================================================================================================================*/
Int16 CSL_gptIntrTest_t1(void)
{

        CSL_Status    status;
        CSL_Config    hwConfig;
        CSL_GptObj    gptObj;
        Uint32        cpuCycleDelta;

        hitIsr   = FALSE;
        status   = 0;

        // Get the System clock value at which CPU is currently running
        /*sysClk = getSysClk();

        // CPU clock cycles that  are 1% of the sysClk" value
        cpuCycleDelta = (sysClk/100);

        printf("\n\nCPU clock is running at %ldKHz\n", sysClk);
        printf("Timer Prescaler Divide Value is Set to Divide by 4\n");
        printf("GPT Runs at Rate 1/4 of the CPU System Clock\n");
        printf("GPT Count is Initialized to 1/4 of CPU Clock Cycles per Millisecond\n");
        printf("With Reference to CPU Clock GPT Will Take 1 Millisecond to Count Down the Timer to 0\n");
        printf("So The CPU Should Execute Approximately %ld(±1%%) Clock Cycles ",sysClk);
        printf("From the Starting of the Timer Till the Expiry of the Timer\n\n");*/

        /* Open the CSL GPT module */
        hGpt = GPT_open (GPT_1, &gptObj, &status);
        if((NULL == hGpt) || (CSL_SOK != status))
        {
                printf("GPT Open Failed\n");
                return (CSL_TEST_FAILED);
        }
        else
        {
                printf("GPT Open Successful\n");
        }

        /* Reset the GPT module */
        status = GPT_reset(hGpt);
        if(CSL_SOK != status)
        {
                printf("GPT Reset Failed\n");
                return (CSL_TEST_FAILED);
        }
        else
        {
                printf("GPT Reset Successful\n");
        }

        /* Clear any pending interrupts */
        IRQ_clearAll();

        /* Disable all the interrupts */
        IRQ_disableAll();

        IRQ_setVecs((Uint32)(&VECSTART));
        IRQ_plug(TINT_EVENT, &gpt1Isr);
        IRQ_enable(TINT_EVENT);

        hwConfig.autoLoad    = GPT_AUTO_ENABLE;
        hwConfig.ctrlTim     = GPT_TIMER_ENABLE;
        hwConfig.preScaleDiv = GPT_PRE_SC_DIV_1;
        //for 1ms
        /* sysClk=sysClk*1000;
        One_cycle=(1/sysClk);
        Time_period=(One_cycle/Desired_time_interval);*/
        //hwConfig.prdLow    = 0x61A8; //1ms
        //hwConfig.prdHigh   = 0x0000;

        hwConfig.prdLow    = 0x00F4; //1us
        hwConfig.prdHigh   = 0x0000;

        // hwConfig.prdLow    = (((sysClk)*5)&0xFFFF);
        // hwConfig.prdHigh   = (((sysClk)*5)>>16);
        //for 20ms 5*sysclk=5*262000=1310000=13FD30
        //for 1000ms=1sec=250*sysclk=250*262000=65500000=03E77360
        //hwConfig.prdLow      = 0x7360;
        //hwConfig.prdHigh     = 0x03E7;

        /* Configure the GPT module */
        status =  GPT_config(hGpt, &hwConfig);
        if(CSL_SOK != status)
        {
                printf("GPT Config Failed\n");
                return (CSL_TEST_FAILED);
        }
        else
        {
                printf("GPT Config Successful\n");
        }

        /* Enable CPU Interrupts */
        IRQ_globalEnable();

        /* Start the Timer */
        GPT_start(hGpt);

        /* Wait for the timer interrupt */
        /* This loop takes 12 CPU cycles to execute on iteration.
        So the CPU cycles executed after starting the timer till the
        expiry of the timer will be 12*cpuCycleCount. */
        while(hitIsr != TRUE)
        {
                cpuCycleCount++;
        }

        /* Disable the CPU interrupts */
        IRQ_globalDisable();

        /* Clear any pending interrupts */
        IRQ_clearAll();

        /* Disable all the interrupts */
        IRQ_disableAll();

        /* Stop the Timer */
        status = GPT_stop(hGpt);
        if(CSL_SOK != status)
        {
                printf("GPT Stop Failed \n");
                return (CSL_TEST_FAILED);
        }
        else
        {
                printf("GPT Stop Successful\n");
        }

        status = GPT_reset(hGpt);

        /* Display the number of CPU cycles executed */
        printf("\nTimer Count Reached Zero\n");
        cpuCycleCount *= 12;
        printf("\n\nNUMBER OF CPU CYCLES EXECUTED AFTER STARTING THE TIMER TILL THE TIMER EXPIRY: ");
        printf("%ld\n", cpuCycleCount);

        /* Test passes if the "cpuCycles" value is in the range
        ((sysClk) ± (1% of sysClk)) */
        if(((cpuCycleCount - cpuCycleDelta) < sysClk) &&
        ((cpuCycleCount + cpuCycleDelta) > sysClk))
        {
                printf("GPT IS RUNNING AT THE CONFIGURED RATE!\n\n");
        }
        else
        {
                printf("GPT IS NOT RUNNING AT THE CONFIGURED RATE!\n\n");
                return (CSL_TEST_FAILED);
        }

        /* Close The GPT Module */
        status = GPT_close(hGpt);
        if(CSL_SOK != status)
        {
                printf("GPT Close Failed\n");
                return (CSL_TEST_FAILED);
        }

        return (CSL_TEST_PASSED);
}
