//###########################################################################
//
// FILE:    standard_interrupt.c
//
// TITLE:
//
// NOTES:
//  1)
//###########################################################################
//
//  Ver  | dd mmm yyyy | Who  		| Description of changes
// ======|=============|============|========================================
//  00 	   05 04 2015 	 HPCS
//
//  Texas Instruments, Inc
//  Copyright Texas Instruments 2008. All rights reserved.
//###########################################################################
#include "system_defines.h"
#include "cyclone_device.h"
#include "variables.h"
#include "function_definitions.h"
#include "software_interrupts.h"
#include "cyclone_defines.h"
#include "pmbus_common.h"
#include "pmbus_topology.h"
#include "pmbus_constants.h"

#define PMW_FREQUENCY 100000 // <--------
#define PWM_CLOCK 15625000
#define PWM_PERIOD (PWM_CLOCK)/(PMW_FREQUENCY)

void poll_adc()
{
	static Uint32 average_count=0;
	static Uint32 _12_V_accumilate=0,_14_8_V_accumilate=0,Iout_1,Iout_2;


	if(AdcRegs.ADCSTAT.bit.ADC_INT == 1 )
		{
			adc_struct.system_voltage=AdcRegs.ADCRESULT[0].all;
			adc_struct.battery_voltage=AdcRegs.ADCRESULT[1].all;
			adc_struct.temp_reading=AdcRegs.ADCRESULT[4].all;

			Iout_1=Iout_1+AdcRegs.ADCRESULT[2].all;
			Iout_2=Iout_2+AdcRegs.ADCRESULT[3].all;

			_12_V_accumilate=_12_V_accumilate+adc_struct.system_voltage;
			_14_8_V_accumilate=_14_8_V_accumilate+adc_struct.battery_voltage;
			average_count++;
			if(average_count == 128)
			{
				wait_done=1;
				adc_struct.system_voltage_avg_32 =_12_V_accumilate >>7;
				adc_struct.battery_voltage_avg_32 =_14_8_V_accumilate >>7;
				adc_struct.battery_current=Iout_1 >>7;
				adc_struct.system_current=Iout_2 >>7;
				adc_struct.Current_sum=adc_struct.battery_current + adc_struct.system_current;
				average_count=0;
				_12_V_accumilate=0;
				_14_8_V_accumilate=0;
				Iout_1=0;
				Iout_2=0;

			}

		}
	AdcRegs.ADCCTRL.bit.SW_START = 1;

}





#pragma INTERRUPT(standard_interrupt,IRQ)
void standard_interrupt(void)
{
	poll_adc();


	 switch(converter_state)
	 {
	 case BOOST_BUCK:
		 	 	boost_buck_handler();
		 	 	 break;
	 case PS_OFF:
			  	 ps_off_handler();
			  	 break;
	 }

	TimerRegs.T16PWM2CMPCTRL.all = 3;
}
