/**
 *******************************************************************************
 * @file  hrpwm/hrpwm_capture_ext_event/source/main.c
 * @brief This example demonstrates HRPWM Capture function.
 @verbatim
   Change Logs:
   Date             Author          Notes
   2024-01-15       CDT             First version
 @endverbatim
 *******************************************************************************
 * Copyright (C) 2022-2024, Xiaohua Semiconductor Co., Ltd. All rights reserved.
 *
 * This software component is licensed by XHSC under BSD 3-Clause license
 * (the "License"); You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *                    opensource.org/licenses/BSD-3-Clause
 *
 *******************************************************************************
 */

/*******************************************************************************
 * Include files
 ******************************************************************************/
#include "main.h"
#include "control.h"
#include "protect.h"
#include "table.h"
#include "stdio.h"
#include "string.h"
#include "calibration.h"
/**
 * @addtogroup HC32F334_DDL_Examples
 * @{
 */

/**
 * @addtogroup HRPWM_Capture_External_Event
 * @{
 */

/*******************************************************************************
 * Local type definitions ('typedef')
 ******************************************************************************/

/*******************************************************************************
 * Local pre-processor symbols/macros ('#define')
 ******************************************************************************/

/*******************************************************************************
 * Global variable definitions (declared in header file with 'extern')
 ******************************************************************************/

/*******************************************************************************
 * Local function prototypes ('static')
 ******************************************************************************/

/*******************************************************************************
 * Local variable definitions ('static')
 ******************************************************************************/
uint8_t Update_CalPar_cmd=0;
uint8_t Mode_delay_flag=0;
uint8_t Calib_mode_1s_Cnt_Delay=0;
uint8_t Mode_Sel_Timer=0;
/*******************************************************************************
 * Function implementation - global ('extern') and local ('static')
 ******************************************************************************/
/**
 * @brief  Main function
 * @param  None
 * @retval int32_t return value, if needed
 */
int32_t main(void)
{
    /* Unlock peripherals or registers */
    LL_PERIPH_WE(EXAMPLE_PERIPH_WE);
    /* Configure BSP */
    BSP_CLK_Init();
	
	  EFM_PrefetchCmd(ENABLE);
	  EFM_DCacheCmd(ENABLE);
	  EFM_ICacheCmd(ENABLE);
    /* Initializes UART for debug printing. Baudrate is 115200. */
    DDL_PrintfInit(BSP_PRINTF_DEVICE, 115200UL, BSP_PRINTF_Preinit);
	 // Usart_init(USART_DEVICE,115200UL);
	  Read_CalPar();
		GPIO_Config();
		Cmp_Config();
		Dac_Config();
		Adc_Config();
		HRPWM_Config();
	  AllPWM_Disable();
		Emb_Config();
    HRPWM_CountStart(HRPWM_FB_1);
		HRPWM_CountStart(HRPWM_FB_2);
	  TmrA_Config();
		
		DDL_Printf("if going into Calibration Mode, Please input 'Y'!\r\n");
		Mode_delay_flag = 0;
		while( Mode_delay_flag == 0 )
		{
			if( Calib_mode_1s_Cnt_Delay != Time_1s_Cnt )
			{
				if( (++Mode_Sel_Timer) > MODE_SEL_DELAY_THRESHOLD )
				{
					Mode_delay_flag = 1;
					SysCali_Cmd=0;
					DDL_Printf("Calibration mode is not enabled!\r\n");
					Mode_Sel_Timer=0;
				}
			}
			Calib_mode_1s_Cnt_Delay = Time_1s_Cnt;
			uint8_t mode_cmd = comm_uart_cal();
			if( mode_cmd == 'Y' )
			{
				Mode_delay_flag = 1;
				SysCali_Cmd=1;
				Mode_Sel_Timer=0;
			}
		}
		if( SysCali_Cmd == 0 )
		{
			WDT_Config();
			WDT_FeedDog();
		}
		
    for (;;) 
		{
			///update calibration parameter
			if( SysCali_Cmd == 1 )
			{
				System_Calib_Statemachine();
				if(Update_CalPar_cmd==1)
				{
					 Write_CalPar();
					 Read_CalPar();
					 Update_CalPar_cmd=0;
				}
		  }
			else
			{
				comm_uart();
			}
      main_func();
			//////////////////////////////////////////////////
			LED_Control();
			//////////////////////////////////////////////////
			WDT_FeedDog();
			//////////////////////////////////////////////////
    }
}

/**
 * @brief  HRPWM capture interrupt handler. for interleave control
 * @param  None
 * @retval None
 */
uint32_t fastint_value=0;
void HRPWM_1_Ovf_Udf_Handler(void)
{
//	  CLR_REG32_BIT(CM_HRPWM1->STFLR1, HRPWM_STFLR1_UDFF);
	  FlyBack_Interleaved_adjustment();
//	  fastint_value=HRPWM_FB_1->CNTER;
}
/**
 * @brief  TIMA capture interrupt handler.for control
 * @param  None
 * @retval None
 */
uint16_t Value1=0,Value2=0,deltavalue=0;
void ADC1_Handler(void)//TMRA_1_Ovf_Udf_Handler(void)//
{
//	Value1 = CM_TMRA_1->CNTER;
	CLR_REG8_BIT(CM_TMRA_1->BCSTRH, TMRA_FLAG_OVF);
	Micro_inverter_CTRL();
//	Value2 = CM_TMRA_1->CNTER;
//	if(deltavalue< (Value2-Value1))
//	{
//	  deltavalue=Value2-Value1;
//	}
}
/**
 * @brief  Configure adc init
 * @param  None 
 *  @arg None
 * @retval None
 */
void Adc_Config(void)
{
//   PWC_FCG0_REG_Unlock();
	 FCG_Fcg3PeriphClockCmd(FCG3_PERIPH_ADC1, ENABLE);
	 FCG_Fcg3PeriphClockCmd(FCG3_PERIPH_ADC2, ENABLE);
	 stc_adc_init_t stcAdcInit;
	(void)ADC_StructInit(&stcAdcInit);
	
	stcAdcInit.u16ScanMode   = ADC_MD_SEQA_SINGLESHOT;
	stcAdcInit.u16Resolution = ADC_RESOLUTION_12BIT;
	stcAdcInit.u16DataAlign  = ADC_DATAALIGN_RIGHT;
	
	(void)ADC_Init(CM_ADC1, &stcAdcInit);
	(void)ADC_Init(CM_ADC2, &stcAdcInit);
	
	 ADC_ChRemap(CM_ADC1, ADC_ICT1_DEST_CH, ADC_ICT1_PIN);
	 ADC_ChRemap(CM_ADC1, ADC_IACL_DEST_CH, ADC_IACL_PIN);
	 ADC_ChRemap(CM_ADC1, ADC_VAC_DEST_CH, ADC_VAC_PIN);
	 ADC_ChRemap(CM_ADC1, ADC_IDC_DEST_CH, ADC_IDC_PIN);
	 
	 ADC_ChRemap(CM_ADC2, ADC_ICT2_DEST_CH, ADC_ICT2_PIN);
	 ADC_ChRemap(CM_ADC2, ADC_IACR_DEST_CH, ADC_IACR_PIN);
	 ADC_ChRemap(CM_ADC2, ADC_VDC_DEST_CH, ADC_VDC_PIN);
	 
	 ADC_ChCmd(CM_ADC1, ADC_SEQ_A, ADC_IACL_DEST_CH, ENABLE);
	 ADC_ChCmd(CM_ADC1, ADC_SEQ_A, ADC_VAC_DEST_CH, ENABLE);
	 ADC_ChCmd(CM_ADC1, ADC_SEQ_A, ADC_IDC_DEST_CH, ENABLE);
	 
	 ADC_ChCmd(CM_ADC2, ADC_SEQ_A, ADC_IACR_DEST_CH, ENABLE);
	 ADC_ChCmd(CM_ADC2, ADC_SEQ_A, ADC_VDC_DEST_CH, ENABLE); 
	 
	 FCG_Fcg0PeriphClockCmd(FCG0_PERIPH_AOS, ENABLE);
	 ADC_TriggerConfig(CM_ADC1, ADC_SEQ_A, ADC_HARDTRIG_EVT0);
	 AOS_SetTriggerEventSrc(AOS_ADC1_0,EVT_SRC_TMRA_1_OVF);
	 ADC_TriggerCmd(CM_ADC1, ADC_SEQ_A, ENABLE);
	 
	 ADC_TriggerConfig(CM_ADC2, ADC_SEQ_A, ADC_HARDTRIG_EVT0);
	 AOS_SetTriggerEventSrc(AOS_ADC2_0, EVT_SRC_TMRA_1_OVF);//EVT_SRC_HRPWM_4_SCMP_A);//
	 ADC_TriggerCmd(CM_ADC2, ADC_SEQ_A, ENABLE);
	 
	  NVIC_ClearPendingIRQ(ADC1_IRQn);
    NVIC_SetPriority(ADC1_IRQn, DDL_IRQ_PRIO_02);
    NVIC_EnableIRQ(ADC1_IRQn);

    ADC_IntCmd(CM_ADC1, ADC_INT_EOCA, ENABLE);  
}
/**
 * @brief  Configure cmp init
 * @param  None 
 *  @arg None
 * @retval None
 */
void Cmp_Config(void)
{
	FCG_Fcg3PeriphClockCmd(FCG3_PERIPH_CMP1_2, ENABLE);
	stc_cmp_init_t stcCmpInit;
	(void)CMP_StructInit(&stcCmpInit);
	
	stcCmpInit.u16PositiveInput = (uint16_t)CMP_POSITIVE_INP1;//CMP_POSITIVE_INP2;//CMP_POSITIVE_INP2;//
	stcCmpInit.u16NegativeInput = (uint16_t)CMP_NEGATIVE_INM3;//CMP_NEGATIVE_INM2;//
	stcCmpInit.u16OutPolarity = CMP_OUT_INVT_OFF;
	stcCmpInit.u16OutDetectEdge = CMP_DETECT_EDGS_BOTH;
	stcCmpInit.u16OutFilter = CMP_OUT_FILTER_NONE;//CMP_OUT_FILTER_CLK_DIV32;
	stcCmpInit.u16HystVoltage = CMP_HYST_VOLT_NONE;//CMP_HYST_VOLT_10MV;//
	(void)CMP_NormalModeInit(CM_CMP1, &stcCmpInit);
	stcCmpInit.u16PositiveInput = (uint16_t)CMP_POSITIVE_INP2;//CMP_POSITIVE_INP1;
	(void)CMP_NormalModeInit(CM_CMP2, &stcCmpInit);
	
	 CMP_CompareOutCmd(CM_CMP1, ENABLE);
	 CMP_CompareOutCmd(CM_CMP2, ENABLE);
	 CMP_PinVcoutCmd(CM_CMP1, ENABLE);
	 CMP_PinVcoutCmd(CM_CMP2, ENABLE);
	
}
/**
 * @brief  Configure DAC init
 * @param  None 
 *  @arg None
 * @retval None
 */
void Dac_Config(void)
{
    FCG_Fcg3PeriphClockCmd(PWC_FCG3_DAC1, ENABLE);
		FCG_Fcg3PeriphClockCmd(PWC_FCG3_DAC2, ENABLE);
	  DAC_DeInit(CM_DAC1);
		DAC_DeInit(CM_DAC2);
    stc_dac_init_t stInit;
    (void)DAC_StructInit(&stInit);
	  stInit.enOutput = DISABLE;
	  (void)DAC_Init(CM_DAC1, DAC_CH1, &stInit);
	  stInit.enOutput = ENABLE;
		(void)DAC_Init(CM_DAC1, DAC_CH2, &stInit);
    (void)DAC_Init(CM_DAC2, DAC_CH1, &stInit);
	
	  DAC_Start(CM_DAC1,DAC_CH1);
	  DAC_Start(CM_DAC1,DAC_CH2);
	  DAC_Start(CM_DAC2,DAC_CH1);
	
	  CM_DAC1->DADR1 = 0;
	  CM_DAC1->DADR2 = 0;
	  CM_DAC2->DADR1 = 0;
    /* Set ADC first */
    /* Enable ADC peripheral clock. */
    FCG_Fcg3PeriphClockCmd(PWC_FCG3_ADC1 | PWC_FCG3_ADC2 | PWC_FCG3_ADC3, ENABLE);
    if (CM_ADC1->STR == 0U) {
        if (CM_ADC2->STR == 0U) {
            if (CM_ADC3->STR == 0U) {
                DAC_ADCPrioConfig(CM_DAC1, DAC_ADP_SEL_ALL, ENABLE);
                DAC_ADCPrioCmd(CM_DAC1, ENABLE);
                DAC_ADCPrioConfig(CM_DAC2, DAC_ADP_SEL_ALL, ENABLE);
                DAC_ADCPrioCmd(CM_DAC2, ENABLE);							  
            }
        }
    }
}
/**
 * @brief  Configure GPIO init
 * @param  None 
 *  @arg None
 * @retval None
 */
void GPIO_Config(void)
{
  //HRPWM
	GPIO_HrpwmPinCmd(GPIO_HRPWM1_PWMA,ENABLE);
	GPIO_HrpwmPinCmd(GPIO_HRPWM4_PWMA,ENABLE);
	//EMB
	GPIO_SetFunc(HRPWM_EMB1_PORT,HRPWM_EMB1_PIN,HRPWM_EMB_FUNC);
	GPIO_SetFunc(HRPWM_EMB2_PORT,HRPWM_EMB2_PIN,HRPWM_EMB_FUNC);
	GPIO_SetFunc(HRPWM_EMB3_PORT,HRPWM_EMB3_PIN,HRPWM_EMB_FUNC);
	GPIO_SetFunc(HRPWM_EMB4_PORT,HRPWM_EMB4_PIN,HRPWM_EMB_FUNC);
	GPIO_SetFunc(HRPWM_EMB5_PORT,HRPWM_EMB5_PIN,HRPWM_EMB_FUNC);
	//cmp inp
	stc_gpio_init_t stcGpioInit;
	(void)GPIO_StructInit(&stcGpioInit);
	stcGpioInit.u16PinAttr = PIN_ATTR_ANALOG;
	(void)GPIO_Init(CMP_INP1_PORT, CMP_INP1_PIN, &stcGpioInit);
	(void)GPIO_Init(CMP_INP2_PORT, CMP_INP2_PIN, &stcGpioInit);
	
	(void)GPIO_SetFunc(CMP1_OUT_PORT, CMP1_OUT_PIN, CMP1_OUT_FUNC);
//	(void)GPIO_SetFunc(CMP2_OUT_PORT, CMP2_OUT_PIN, CMP2_OUT_FUNC);
	//ADC
	(void)GPIO_Init(GPIO_ICT1_PORT, GPIO_ICT1_PIN, &stcGpioInit);
	(void)GPIO_Init(GPIO_IACL_PORT, GPIO_IACL_PIN, &stcGpioInit);
	(void)GPIO_Init(GPIO_VAC_PORT, GPIO_VAC_PIN, &stcGpioInit);
	(void)GPIO_Init(GPIO_IDC_PORT, GPIO_IDC_PIN, &stcGpioInit);
	(void)GPIO_Init(GPIO_ICT2_PORT, GPIO_ICT2_PIN, &stcGpioInit);
	(void)GPIO_Init(GPIO_IACR_PORT, GPIO_IACR_PIN, &stcGpioInit);
	(void)GPIO_Init(GPIO_VDC_PORT, GPIO_VDC_PIN, &stcGpioInit);
	//DAC
	(void)GPIO_Init(DAC1_OUTPUT2_PORT, DAC1_OUTPUT2_PIN, &stcGpioInit);
	(void)GPIO_Init(DAC2_OUTPUT1_PORT, DAC2_OUTPUT1_PIN, &stcGpioInit);
	
	//unfolding
	stcGpioInit.u16PinState       = PIN_STAT_RST;
	stcGpioInit.u16PinDir         = PIN_DIR_OUT;
	stcGpioInit.u16PinDrv         = PIN_LOW_DRV;
	stcGpioInit.u16PinAttr        = PIN_ATTR_DIGITAL;
  (void)GPIO_Init(UNFOLDING_SCR_L_PORT, UNFOLDING_SCR_L_PIN, &stcGpioInit);
	(void)GPIO_Init(UNFOLDING_SCR_R_PORT, UNFOLDING_SCR_R_PIN, &stcGpioInit);
	(void)GPIO_Init(UNFOLDING_MOS_L_PORT, UNFOLDING_MOS_L_PIN, &stcGpioInit);
	(void)GPIO_Init(UNFOLDING_MOS_R_PORT, UNFOLDING_MOS_R_PIN, &stcGpioInit);
	 stcGpioInit.u16PinDrv         = PIN_LOW_DRV;
	(void)GPIO_Init(LED_GREEN_PORT, LED_GREEN_PIN, &stcGpioInit);
	(void)GPIO_Init(LED_RED_PORT, LED_RED_PIN, &stcGpioInit);
	///usart
	GPIO_SetDebugPort(GPIO_PIN_TDI,DISABLE);
	GPIO_SetFunc(USART_TX_PORT, USART_TX_PIN, USART_TX_PORT_FUNC);
	GPIO_SetFunc(USART_RX_PORT, USART_RX_PIN, USART_RX_PORT_FUNC);
}
/**
 * @brief  Configure EMB init
 * @param  None 
 *  @arg None
 * @retval None
 */
void Emb_Config(void)
{
	FCG_Fcg2PeriphClockCmd(FCG2_PERIPH_EMB, ENABLE);
	stc_emb_hrpwm_init_t stcEmbInit;
	stc_hrpwm_emb_config_t stcHrpwmEmbConfig;
	(void)HRPWM_EMB_StructInit(&stcHrpwmEmbConfig);
	(void)EMB_HRPWM_StructInit(&stcEmbInit);
	
	(void)HRPWM_EMB_StructInit(&stcHrpwmEmbConfig);
	stcHrpwmEmbConfig.u32ValidCh = HRPWM_EMB_EVT_CH0;
	stcHrpwmEmbConfig.u32ReleaseMode = HRPWM_EMB_RELEASE_IMMED;
	stcHrpwmEmbConfig.u32PinStatus = HRPWM_EMB_PIN_LOW;
	(void)HRPWM_EMB_ChAConfig(HRPWM_FB_1, &stcHrpwmEmbConfig);
	(void)HRPWM_EMB_ChAConfig(HRPWM_FB_2, &stcHrpwmEmbConfig);
	
	(void)EMB_HRPWM_StructInit(&stcEmbInit);
	stcEmbInit.stcPort.stcPort1.u32PortState       = EMB_PORT1_ENABLE;
	stcEmbInit.stcPort.stcPort1.u32PortLevel       = EMB_PORT1_DETECT_LVL_HIGH;
	stcEmbInit.stcPort.stcPort1.u32PortFilterDiv   = EMB_PORT1_FILTER_CLK_DIV1;
	stcEmbInit.stcPort.stcPort1.u32PortFilterState = EMB_PORT1_FILTER_ENABLE;
	stcEmbInit.stcPort.stcPort2.u32PortState       = EMB_PORT2_ENABLE;
	stcEmbInit.stcPort.stcPort2.u32PortLevel       = EMB_PORT2_DETECT_LVL_HIGH;
	stcEmbInit.stcPort.stcPort2.u32PortFilterDiv   = EMB_PORT2_FILTER_CLK_DIV1;
	stcEmbInit.stcPort.stcPort2.u32PortFilterState = EMB_PORT2_FILTER_ENABLE;
	stcEmbInit.stcPort.stcPort3.u32PortState       = EMB_PORT3_ENABLE;
	stcEmbInit.stcPort.stcPort3.u32PortLevel       = EMB_PORT3_DETECT_LVL_HIGH;
	stcEmbInit.stcPort.stcPort3.u32PortFilterDiv   = EMB_PORT3_FILTER_CLK_DIV1;
	stcEmbInit.stcPort.stcPort3.u32PortFilterState = EMB_PORT3_FILTER_ENABLE;
	stcEmbInit.stcPort.stcPort4.u32PortState       = EMB_PORT4_ENABLE;
	stcEmbInit.stcPort.stcPort4.u32PortLevel       = EMB_PORT4_DETECT_LVL_HIGH;
	stcEmbInit.stcPort.stcPort4.u32PortFilterDiv   = EMB_PORT4_FILTER_CLK_DIV1;
	stcEmbInit.stcPort.stcPort4.u32PortFilterState = EMB_PORT4_FILTER_ENABLE;
	stcEmbInit.stcPort.stcPort5.u32PortState       = EMB_PORT5_ENABLE;
	stcEmbInit.stcPort.stcPort5.u32PortLevel       = EMB_PORT5_DETECT_LVL_HIGH;
	stcEmbInit.stcPort.stcPort5.u32PortFilterDiv   = EMB_PORT5_FILTER_CLK_DIV1;
	stcEmbInit.stcPort.stcPort5.u32PortFilterState = EMB_PORT5_FILTER_ENABLE;
	stcEmbInit.stcPort.u32PortFilterCount          = EMB_PORT_FILTER_CNT_3;
	(void)EMB_HRPWM_Init(CM_EMB0, &stcEmbInit);
	
	EMB_ClearStatus(CM_EMB0,EMB_FLAG_PORT1);
	EMB_ClearStatus(CM_EMB0,EMB_FLAG_PORT2);
	EMB_ClearStatus(CM_EMB0,EMB_FLAG_PORT3);
	EMB_ClearStatus(CM_EMB0,EMB_FLAG_PORT4);
	EMB_ClearStatus(CM_EMB0,EMB_FLAG_PORT5);
	EMB_ClearStatus(CM_EMB0,EMB_FLAG_SYS);
	
	EMB_SetReleasePwmCond(CM_EMB0, EMB_EVT_PORT1, EMB_RELEASE_PWM_COND_FLAG_ZERO);
	EMB_SetReleasePwmCond(CM_EMB0, EMB_EVT_PORT2, EMB_RELEASE_PWM_COND_FLAG_ZERO);
	EMB_SetReleasePwmCond(CM_EMB0, EMB_EVT_PORT3, EMB_RELEASE_PWM_COND_FLAG_ZERO);
	EMB_SetReleasePwmCond(CM_EMB0, EMB_EVT_PORT4, EMB_RELEASE_PWM_COND_FLAG_ZERO);
	EMB_SetReleasePwmCond(CM_EMB0, EMB_EVT_PORT5, EMB_RELEASE_PWM_COND_FLAG_ZERO);
	EMB_SetReleasePwmCond(CM_EMB0, EMB_EVT_SYS, EMB_RELEASE_PWM_COND_FLAG_ZERO);

}
/**
 * @brief  Configure PWM capture input
 * @param  [in] HRPWMx               HRPWM unit
 *  @arg CM_HRPWM_x
 * @retval None
 */
void HRPWM_Config(void)
{
	
	  FCG_Fcg2PeriphClockCmd(HRPWM_FB1_FCG, ENABLE);
	  FCG_Fcg2PeriphClockCmd(HRPWM_FB2_FCG, ENABLE);
    FCG_Fcg0PeriphClockCmd(FCG0_PERIPH_AOS, ENABLE);

    HRPWM_CommonDeInit();
    HRPWM_DeInit(HRPWM_FB_1);
	  HRPWM_DeInit(HRPWM_FB_2);
	

    /* Calibrate */
    if (LL_OK != HRPWM_CALIB_ProcessSingle()) {
//        DDL_Printf("HRPWM calibrate failed!\r\n");
        for (;;) {
            /* Calibrate failed */
        }
    }
//    DDL_Printf("HRPWM calibrate success!\r\n");
		
		/* HRPWM function enable */
    HRPWM_Enable(HRPWM_FB_1);
		HRPWM_Enable(HRPWM_FB_2);
		
    stc_hrpwm_init_t stcHrpwmInit;
	  stc_hrpwm_pwm_init_t stcPwmInit;
	  stc_hrpwm_pwm_output_init_t stcPwmOutputInit;
	  stc_hrpwm_buf_config_t stcBufConfigInit;
	  stc_hrpwm_evt_config_t stcEvtConfigInit;
	  stc_hrpwm_evt_filter_config_t stcEvtFilterConfigInit;
	  stc_hrpwm_evt_filter_signal_config_t stcEvtFilterSignalConfigInit;

    (void)HRPWM_StructInit(&stcHrpwmInit);
	  (void)HRPWM_PWM_StructInit(&stcPwmInit);
	  (void)HRPWM_PWM_OutputStructInit(&stcPwmOutputInit);
		(void)HRPWM_BufStructInit(&stcBufConfigInit);
	  (void)HRPWM_EVT_StructInit(&stcEvtConfigInit);
	  (void)HRPWM_EVT_FilterStructInit(&stcEvtFilterConfigInit);
	  (void)HRPWM_EVT_FilterSignalStructInit(&stcEvtFilterSignalConfigInit);
	
		stcEvtConfigInit.u32EventSrc = HRPWM_EVT_SRC2;
		stcEvtConfigInit.u32EventSrc2 = HRPWM_EVT_SRC2_CMP1;
		stcEvtConfigInit.u32ValidLevel = HRPWM_EVT_VALID_LVL_LOW;
		stcEvtConfigInit.u32ValidAction = HRPWM_EVT_VALID_FALLING;
		stcEvtConfigInit.u32FastAsyncMode = HRPWM_EVT_FAST_ASYNC_OFF;
		stcEvtConfigInit.u32FilterClock = HRPWM_EVT_FILTER_NONE;
		stcEvtConfigInit.u32ExtEvtDetect = HRPWM_EVT_GEN_DETECT_OFF;
	  HRPWM_EVT_Config(HRPWM_EVT1,&stcEvtConfigInit);
	  stcEvtConfigInit.u32EventSrc2 = HRPWM_EVT_SRC2_CMP2;
	  HRPWM_EVT_Config(HRPWM_EVT2,&stcEvtConfigInit);
		
		stcEvtFilterConfigInit.u32Mode = HRPWM_EVT_FILTER_MD_BLANK_U1;
		stcEvtFilterConfigInit.u32Latch = HRPWM_EVT_FILTER_LATCH_OFF;
		stcEvtFilterConfigInit.u32WindowTimeout = HRPWM_EVT_FILTER_TIMEOUT_OFF;
		HRPWM_EVT_FilterConfig(HRPWM_FB_1,HRPWM_EVT1,&stcEvtFilterConfigInit);
		HRPWM_EVT_FilterConfig(HRPWM_FB_2,HRPWM_EVT2,&stcEvtFilterConfigInit);
		
		HRPWM_EVT_FilterSetReplaceMode(HRPWM_FB_1,HRPWM_EVT_FILTER_REPLACE_MD2_PEAK);
	  HRPWM_EVT_FilterSetReplaceMode(HRPWM_FB_2,HRPWM_EVT_FILTER_REPLACE_MD2_PEAK);
		
		stcEvtFilterSignalConfigInit.u32InitPolarity = HRPWM_EVT_FILTER_INIT_POLARITY_LOW;
		stcEvtFilterSignalConfigInit.u32Offset = 130000UL;
		stcEvtFilterSignalConfigInit.u32OffsetDir = HRPWM_EVT_FILTER_OFS_DIR_UP;
		stcEvtFilterSignalConfigInit.u32Window = 0x00UL;
		stcEvtFilterSignalConfigInit.u32WindowDir = HRPWM_EVT_FILTER_WIN_DIR_UP;
		HRPWM_EVT_FilterSignalConfig(HRPWM_FB_1,&stcEvtFilterSignalConfigInit);
		HRPWM_EVT_FilterSignalConfig(HRPWM_FB_2,&stcEvtFilterSignalConfigInit);
		
		
		AOS_SetTriggerEventSrc(AOS_HRPWM0,EVT_SRC_HRPWM_4_OVF);
			
    /* HRPWM general count function configure */
    stcHrpwmInit.u32CountMode = HRPWM_MD_SAWTOOTH;
    stcHrpwmInit.u32CountReload = HRPWM_CNT_RELOAD_ON;
    stcHrpwmInit.u32PeriodValue = PERIOD_MAX;
    (void)HRPWM_Init(HRPWM_FB_1, &stcHrpwmInit);
	  (void)HRPWM_Init(HRPWM_FB_2, &stcHrpwmInit);

		HRPWM_HWClearCondEnable(HRPWM_FB_1,HRPWM_HW_CLR_COND_EXTEVT1);
		HRPWM_HWClearEnable(HRPWM_FB_1);
		HRPWM_HWClearCondEnable(HRPWM_FB_2,HRPWM_HW_CLR_COND_EXTEVT2);
		HRPWM_HWClearEnable(HRPWM_FB_2);
	
		stcPwmInit.u32CompareValue = 0xD0;
		stcPwmInit.u32StartPolarity = HRPWM_PWM_START_LOW;
		stcPwmInit.u32StopPolarity = HRPWM_PWM_STOP_LOW;
		stcPwmInit.u32PeakPolarity = HRPWM_PWM_PEAK_LOW;
		stcPwmInit.u32ValleyPolarity = HRPWM_PWM_VALLEY_LOW;
		stcPwmInit.u32UpMatchAPolarity = HRPWM_PWM_UP_MATCH_A_LOW;
		stcPwmInit.u32DownMatchAPolarity = HRPWM_PWM_DOWN_MATCH_A_HOLD;
		stcPwmInit.u32UpMatchBPolarity = HRPWM_PWM_UP_MATCH_B_HIGH;
		stcPwmInit.u32DownMatchBPolarity = HRPWM_PWM_DOWN_MATCH_B_HOLD;
		stcPwmInit.u32UpMatchEPolarity = HRPWM_PWM_UP_MATCH_E_HOLD;
		stcPwmInit.u32DownMatchEPolarity = HRPWM_PWM_DOWN_MATCH_E_HOLD;
		stcPwmInit.u32UpMatchFPolarity = HRPWM_PWM_UP_MATCH_F_HOLD;
		stcPwmInit.u32DownMatchFPolarity = HRPWM_PWM_DOWN_MATCH_F_HOLD;
		stcPwmInit.u32UpMatchSpecialAPolarity = HRPWM_PWM_UP_MATCH_SPECIAL_A_HOLD;
		stcPwmInit.u32DownMatchSpecialAPolarity = HRPWM_PWM_DOWN_MATCH_SPECIAL_A_HOLD;
		stcPwmInit.u32UpMatchSpecialBPolarity = HRPWM_PWM_UP_MATCH_SPECIAL_B_HOLD;
		stcPwmInit.u32DownMatchSpecialBPolarity = HRPWM_PWM_DOWN_MATCH_SPECIAL_B_HOLD;
		HRPWM_PWM_ChAInit(HRPWM_FB_1,&stcPwmInit);
		HRPWM_PWM_ChAInit(HRPWM_FB_2,&stcPwmInit);
	
		stcPwmOutputInit.u32ChSwapMode = HRPWM_PWM_CH_SWAP_MD_NOT_IMMED;
		stcPwmOutputInit.u32ChSwap = HRPWM_PWM_CH_SWAP_OFF;
		stcPwmOutputInit.u32ChAInvert = HRPWM_PWM_CHA_INVT_OFF;
		stcPwmOutputInit.u32ChBInvert = HRPWM_PWM_CHB_INVT_OFF;
		HRPWM_PWM_OutputInit(HRPWM_FB_1,&stcPwmOutputInit);
		HRPWM_PWM_OutputInit(HRPWM_FB_2,&stcPwmOutputInit);
		
		stcBufConfigInit.u32BufTransCond = HRPWM_BUF_TRANS_PEAK;
		stcBufConfigInit.enBufTransU1Single = DISABLE;
		stcBufConfigInit.enBufTransAfterU1Single = DISABLE;
		HRPWM_GeneralAEBufConfig(HRPWM_FB_1,&stcBufConfigInit);
		HRPWM_GeneralAEBufConfig(HRPWM_FB_2,&stcBufConfigInit);
		HRPWM_GeneralAEBufEnable(HRPWM_FB_1);
		HRPWM_GeneralAEBufEnable(HRPWM_FB_2);
		
		HRPWM_GeneralBFBufConfig(HRPWM_FB_1,&stcBufConfigInit);
		HRPWM_GeneralBFBufConfig(HRPWM_FB_2,&stcBufConfigInit);
		HRPWM_GeneralBFBufEnable(HRPWM_FB_1);
		HRPWM_GeneralBFBufEnable(HRPWM_FB_2);
		
		stcBufConfigInit.u32BufTransCond = HRPWM_BUF_TRANS_PEAK;
		HRPWM_EVT_OffsetBufConfig(HRPWM_FB_1,&stcBufConfigInit);
		HRPWM_EVT_OffsetBufConfig(HRPWM_FB_2,&stcBufConfigInit);
		HRPWM_EVT_OffsetBufEnable(HRPWM_FB_1);
		HRPWM_EVT_OffsetBufEnable(HRPWM_FB_2);	

	
		HRPWM_PWM_ChAOutputEnable(HRPWM_FB_1);
		HRPWM_PWM_ChAOutputEnable(HRPWM_FB_2);
		
    /* Hardware capture */
    HRPWM_HWChACaptureCondEnable(HRPWM_FB_1,HRPWM_HW_CAPT_COND_EXTEVT1);
    HRPWM_HWChACaptureEnable(HRPWM_FB_1);
    HRPWM_HWChBCaptureCondEnable(HRPWM_FB_1,HRPWM_HW_CAPT_COND_INTERN_EVT0);
    HRPWM_HWChBCaptureEnable(HRPWM_FB_1);	


    /* NVIC config */
    NVIC_ClearPendingIRQ(HRPWM_1_OVF_UDF_IRQn);
    NVIC_SetPriority(HRPWM_1_OVF_UDF_IRQn, DDL_IRQ_PRIO_00);
    NVIC_EnableIRQ(HRPWM_1_OVF_UDF_IRQn);
    /* Enable interrupt */
    HRPWM_IntEnable(HRPWM_FB_1, HRPWM_INT_CNT_VALLEY);
	
}
/**
 * @brief  TimerA configuration.
 * @param  None
 * @retval None
 */
void TmrA_Config(void)
{
    stc_tmra_init_t stcTmraInit;

    /* 1. Enable TimerA peripheral clock. */
    FCG_Fcg2PeriphClockCmd(FCG2_PERIPH_TMRA_1, ENABLE);

    /* 2. Set a default initialization value for stcTmraInit. */
    (void)TMRA_StructInit(&stcTmraInit);

    /* 3. Modifies the initialization values depends on the application. */
    stcTmraInit.sw_count.u8ClockDiv  = TMRA_CLK_DIV1;
    stcTmraInit.sw_count.u8CountMode = TMRA_MD_SAWTOOTH;
    stcTmraInit.sw_count.u8CountDir  = TMRA_DIR_UP;
    stcTmraInit.u32PeriodValue = CTRL_PERIOD_VAL;
    (void)TMRA_Init(CM_TMRA_1, &stcTmraInit);

    /* 4. Configures IRQ if needed. */
//    NVIC_ClearPendingIRQ(TMRA_1_OVF_UDF_IRQn);
//    NVIC_SetPriority(TMRA_1_OVF_UDF_IRQn, DDL_IRQ_PRIO_01);
//    NVIC_EnableIRQ(TMRA_1_OVF_UDF_IRQn);

//    /* Enable the specified interrupts of TimerA. */
//    TMRA_IntCmd(CM_TMRA_1, TMRA_INT_OVF, ENABLE);
		
		TMRA_Start(CM_TMRA_1);
}
/**
 * @brief  TimerA configuration.
 * @param  None
 * @retval None
 */
void WDT_Config(void)
{
    stc_wdt_init_t stcWdtInit;

    /* WDT configuration */
    stcWdtInit.u32CountPeriod   = WDT_CNT_PERIOD4096;
    stcWdtInit.u32ClockDiv      = WDT_CLK_DIV4;
    stcWdtInit.u32RefreshRange  = WDT_RANGE_0TO100PCT;
    stcWdtInit.u32LPMCount      = WDT_LPM_CNT_CONT;
    stcWdtInit.u32ExceptionType = WDT_EXP_TYPE_RST;
    (void)WDT_Init(&stcWdtInit);
}
/**
 * @brief  USART configuration.
 * @param  None
 * @retval None
 */
int32_t Usart_init(void *USART, uint32_t u32Baudrate)
{
    uint32_t u32Div;
    float32_t f32Error;
    stc_usart_uart_init_t stcUartInit;
    int32_t i32Ret = LL_ERR_INVD_PARAM;

    if (0UL != u32Baudrate) {
        /* Enable clock  */
        FCG_Fcg3PeriphClockCmd(USART_FCG, ENABLE);

        /* Configure UART */
        (void)USART_UART_StructInit(&stcUartInit);
        stcUartInit.u32OverSampleBit = USART_OVER_SAMPLE_8BIT;
			  stcUartInit.u32HWFlowControl = USART_HW_FLOWCTRL_NONE;
        (void)USART_UART_Init(USART, &stcUartInit, NULL);

        for (u32Div = 0UL; u32Div <= USART_CLK_DIV64; u32Div++) {
            USART_SetClockDiv(USART, u32Div);
            i32Ret = USART_SetBaudrate(USART, u32Baudrate, &f32Error);
            if ((LL_OK == i32Ret) && \
                ((-USART_BAUDRATE_ERR_MAX <= f32Error) && (f32Error <= USART_BAUDRATE_ERR_MAX))) {
                USART_FuncCmd(USART, USART_TX, ENABLE);
								USART_FuncCmd(USART, USART_RX, ENABLE);
                break;
            } else {
                i32Ret = LL_ERR;
            }
        }
    }

    return i32Ret;
}
///////////////////Led control/////////////////
//control LED to indicate the system status
//input: system state
//output: LED control
//////////////Related variable definition///////////////////
uint32_t twinkle_cnt=0;
uint8_t twinkle_flag=0;
uint16_t MicroInv_Fault_Flag_pre;
////////////////////////////////////////////////////////////
inline void LED_Control(void)
{
	 if( twinkle_cnt > TWINKLE_INTERVAL_THRESHOLD)
	 {
		 twinkle_cnt = 0;
		 twinkle_flag = 1 - twinkle_flag;
	 }
	 else
	 {
		 twinkle_cnt++;
	 }
   //Green LED
	 if( MicroInv_State == STANDBY )
	 {
		 LED_GREEN_ON;
	 }
	 else if( MicroInv_State == FAULT )
	 {
		 LED_GREEN_OFF;
	 }
	 else
	 {
		 if( twinkle_flag == 1 )
		 {
			 LED_GREEN_ON;
		 }
		 else
		 {
			 LED_GREEN_OFF;
		 }
	 }
	 
	 //red LED
	 if( MicroInv_Fault_Flag.all != MicroInv_Fault_Flag_pre )
	 {
		 MicroInv_Fault_Flag_pre = MicroInv_Fault_Flag.all;
		 if( MicroInv_Fault_Flag.all != 0 )
		 {
				LED_RED_ON;
		 }
		 else
		 {
			 LED_RED_OFF;
		 }
   }
	 else
	 {
		 ;
	 } 
}
/////////////////////coummunication/////////////////////
//status for monitor and cmd from 
//input: system state
//output: LED control
//////////////Related variable definition///////////////////
uint8_t TX_Frame[10]={0};
uint8_t System_status_upload_cmd=0;
uint16_t Tx_count=0;
uint32_t TEST_TIME_THRESHOLD=0;
float_t cur_set_value = 0.5f;
uint32_t MicroInv_Fault_Flag_upload_pre=0;
int test=0;
uint16_t Time_100ms_Cnt_Cal_Delay=0;
uint8_t Calib_Mode_Cmd=0;
////////////////////////////////////////////////////////////
inline void comm_uart(void)
{
	  if( UART_RX_NEMPITY == 1 )
		{
			uint8_t buffer = CM_USART2->RDR;
			if(buffer=='A')//start
			{
				MicroInv_Start_cmd = 1;
				System_status_upload_cmd=1;
			}
			else if(buffer=='S')//stop
			{
				MicroInv_Start_cmd = 0;
				System_status_upload_cmd=1;
			}
			else if(buffer=='C')//fault clr
			{
				System_Fault_CLR_cmd=1;
				System_status_upload_cmd=1;
			}
			else if(buffer=='D')//fault clr over
			{
				System_Fault_CLR_cmd=0;
				System_status_upload_cmd=1;
			}
			else if(buffer=='B')
			{
				System_status_upload_cmd=1;
			}
			else if(buffer=='X')
			{
					TEST_TIME_THRESHOLD = TEST_TIME_THRESHOLD+2;
			}
			else if(buffer=='Y')
			{
					TEST_TIME_THRESHOLD = TEST_TIME_THRESHOLD-2;
			}
			else if(buffer=='H')
			{
					 cur_set_value = cur_set_value + 0.1f;
			}
			else if(buffer=='M')
			{
					 cur_set_value = cur_set_value - 0.1f;
			}		
		}
		
		if( System_status_upload_cmd==1 )
		{

		TX_Frame[0] = MicroInv_State;
		TX_Frame[1] = MicroInv_Fault_Flag.all>>8;
		TX_Frame[2] = MicroInv_Fault_Flag.all;
		TX_Frame[3] = TEST_TIME_THRESHOLD>>8;
		TX_Frame[4] = TEST_TIME_THRESHOLD;
		TX_Frame[5] = CalibPara_Done_Flag;
		TX_Frame[6] = ((uint16_t)(Interleave_ratio*1000.0f))>>8;
		TX_Frame[7] = ((uint16_t)(Interleave_ratio*1000.0f));
		TX_Frame[8] = 0;
		TX_Frame[9] = 0;
		}
		
		if( UART_TXFIFO_EMPITY && System_status_upload_cmd==1 )
		{			
			CM_USART2->TDR = TX_Frame[Tx_count++];
			if( Tx_count > 9)
			{
				System_status_upload_cmd = 0;
				Tx_count = 0;
			}
		}
		else
		{
			;
		}	
		
		if( bCM_USART2->SR_b.ORE == 1 )
		{
		   CM_USART2->CR1 |= USART_CR1_CORE;
		}
}

///////////////////write calibration parameter////////////////
//////////////////////////////////////////////////////////////
void Write_CalPar(void)
{
	EFM_REG_Unlock();
	EFM_FWMC_Cmd(ENABLE);
	(void)EFM_SingleSectorOperateCmd(31, ENABLE);
	uint32_t u32Addr = EFM_SECTOR_ADDR(31);
	(void)EFM_SectorErase(u32Addr);
	
	float_t temp=1234.0f;
	EFM_ProgramWord((u32Addr),(*(uint32_t *)(&temp)));
	
	temp=IFB2_GAIN;
	EFM_ProgramWord((u32Addr+0x0004),(*(uint32_t *)(&temp)));
	temp=IFB2_OFFSET;
	EFM_ProgramWord((u32Addr+0x0008),(*(uint32_t *)(&temp)));
	
	temp=IFB1_GAIN;
	EFM_ProgramWord((u32Addr+0x000C),(*(uint32_t *)(&temp)));
	temp=IFB1_OFFSET;
	EFM_ProgramWord((u32Addr+0x0010),(*(uint32_t *)(&temp)));
	
	temp=VPV_GAIN;
	EFM_ProgramWord((u32Addr+0x0014),(*(uint32_t *)(&temp)));
	temp=VPV_OFFSET;
	EFM_ProgramWord((u32Addr+0x0018),(*(uint32_t *)(&temp)));
	
	temp=IGL_GAIN;
	EFM_ProgramWord((u32Addr+0x001C),(*(uint32_t *)(&temp)));
	temp=IGL_OFFSET;
	EFM_ProgramWord((u32Addr+0x0020),(*(uint32_t *)(&temp)));
	
	temp=IGR_GAIN;
	EFM_ProgramWord((u32Addr+0x0024),(*(uint32_t *)(&temp)));
	temp=IGR_OFFSET;
	EFM_ProgramWord((u32Addr+0x0028),(*(uint32_t *)(&temp)));
	
	temp=IPV_GAIN;
	EFM_ProgramWord((u32Addr+0x002C),(*(uint32_t *)(&temp)));
	temp=IPV_OFFSET;
	EFM_ProgramWord((u32Addr+0x0030),(*(uint32_t *)(&temp)));
	
	temp=VGRID_GAIN;
	EFM_ProgramWord((u32Addr+0x0034),(*(uint32_t *)(&temp)));
	temp=VGRID_OFFSET;
	EFM_ProgramWord((u32Addr+0x0038),(*(uint32_t *)(&temp)));
	
	temp=ZCD_CAL_GAIN;
	EFM_ProgramWord((u32Addr+0x003C),(*(uint32_t *)(&temp)));
	
	DDL_Printf("Writing the calibration parameters to flash is successful\r\n");
}

///////////////////Read calibration parameter////////////////
//////////////////////////////////////////////////////////////
float_t IFB2_Gain_par=0.0f;
float_t	IFB2_Offset_par=0.0f;
float_t	IFB1_Gain_par=0.0f;
float_t	IFB1_Offset_par=0.0f;
float_t	Vpv_Gain_par=0.0f;
float_t	Vpv_Offset_par=0.0f;
	
float_t	IgL_Gain_par=0.0f;
float_t	IgL_Offset_par=0.0f;
float_t	IgR_Gain_par=0.0f;
float_t	IgR_Offset_par=0.0f;
float_t	Ipv_Gain_par=0.0f;
float_t	Ipv_Offset_par=0.0f;
float_t	Vgrid_Gain_par=0.0f;
float_t	Vgrid_Offset_par=0.0f;
float_t ZCD_gain_par=0.0f;

uint8_t CalibPara_Done_Flag=0;
/////////////////////////////////////////////
void Read_CalPar(void)
{
	uint32_t u32Addr = EFM_SECTOR_ADDR(31);
	
	CalibPara_Done_Flag = ((*(float *)u32Addr)==1234.0f);
	
	if( CalibPara_Done_Flag == 0 )
	{
		DDL_Printf("There are no calibration parameters!\r\n");
	}
	if( CalibPara_Done_Flag == 1 )
	{
		IFB2_Gain_par = *(float *)(u32Addr+0x0004);
		IFB2_Offset_par = *(float *)(u32Addr+0x0008);
		
		IFB1_Gain_par = *(float *)(u32Addr+0x000C);
		IFB1_Offset_par = *(float *)(u32Addr+0x0010);
		
		Vpv_Gain_par = *(float *)(u32Addr+0x0014);
		Vpv_Offset_par = *(float *)(u32Addr+0x0018);
		
		IgL_Gain_par = *(float *)(u32Addr+0x001C);
		IgL_Offset_par = *(float *)(u32Addr+0x0020);
		
		IgR_Gain_par = *(float *)(u32Addr+0x0024);
		IgR_Offset_par = *(float *)(u32Addr+0x0028);
		
		Ipv_Gain_par = *(float *)(u32Addr+0x002C);
		Ipv_Offset_par = *(float *)(u32Addr+0x0030);
		
		Vgrid_Gain_par = *(float *)(u32Addr+0x0034);
		Vgrid_Offset_par = *(float *)(u32Addr+0x0038);	

		ZCD_gain_par = *(float *)(u32Addr+0x003C);	
	
		IFB2_GAIN = IFB2_Gain_par;
		IFB2_OFFSET = IFB2_Offset_par;
		IFB1_GAIN = IFB1_Gain_par;
		IFB1_OFFSET = IFB1_Offset_par;
		IGL_GAIN = IgL_Gain_par;
		IGL_OFFSET = IgL_Offset_par;
		IGR_GAIN = IgR_Gain_par;
		IGR_OFFSET = IgR_Offset_par;
		IPV_GAIN = Ipv_Gain_par;
		IPV_OFFSET = Ipv_Offset_par;
		ZCD_CAL_GAIN = ZCD_gain_par;

		VPV_GAIN = Vpv_Gain_par;
		VPV_OFFSET = Vpv_Offset_par;
		VGRID_GAIN = Vgrid_Gain_par;
		VGRID_OFFSET = Vgrid_Offset_par;
	}
}

/*******************************************************************************
 * EOF (not truncated)
 ******************************************************************************/
