#include "ys32md211.h"
#include "delay.h"
#include "ys32md211_tim.h"
#include "pwm.h"
#include "motor.h"
#include "adc.h"
//***********************************************************************//
uint16_t TimerPeriod = 0;
uint16_t Channel1Pulse = 0;
uint16_t PwmCap_Cycle = 0;
uint16_t PwmCap_CycleAvg = 0;

uint16_t PwmCap_Duty = 0;
uint16_t PwmCap_DutyAvg = 0;
// NVIC ?????
void TIM1_NVIC_Configuration(void)
{
  NVIC_InitTypeDef NVIC_InitStructure;

  //
  NVIC_InitStructure.NVIC_IRQChannel = TIM1_CC_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
}
//**********************************************************************//
 void TIM1_PWM_Config(void)
{
    TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
    TIM_OCInitTypeDef  TIM_OCInitStructure;
    TIM_BDTRInitTypeDef TIM_BDTRInitStructure;
    GPIO_InitTypeDef GPIO_InitStructure;

    /* GPIOA, GPIOB Clocks enable */
    RCC_AHB2PeriphClockCmd( RCC_AHB2Periph_GPIOA , ENABLE);
    
	   /* GPIOA Configuration: Channel 1, 2, 3, 4 and Channel 1N as alternate function push-pull */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11|GPIO_Pin_12| GPIO_Pin_15; 
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;// GPIO_Mode_OUT;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_VeryHigh;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd =  GPIO_PuPd_NOPULL;//
    GPIO_Init(GPIOA, &GPIO_InitStructure);

	 
	 GPIO_PinAFConfig(GPIOA, GPIO_PinSource15, GPIO_AF_4);
	 GPIO_PinAFConfig(GPIOA, GPIO_PinSource12, GPIO_AF_8);
	 GPIO_PinAFConfig(GPIOA, GPIO_PinSource11, GPIO_AF_8);
	
	 GPIO_PinAFConfig(GPIOA, GPIO_PinSource8, GPIO_AF_11);
	 GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_9);
	 GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_9);
 

    /* TIM1 Configuration ---------------------------------------------------
    Generate 7 PWM signals with 4 different duty cycles:
    TIM1 input clock (TIM1CLK) is set to APB2 clock (PCLK2)    
    => TIM1CLK = PCLK2 = SystemCoreClock
    TIM1CLK = SystemCoreClock, Prescaler = 0, TIM1 counter clock = SystemCoreClock
    SystemCoreClock is set to 24 MHz 

    The objective is to generate 7 PWM signal at 17.57 KHz:
     - TIM1_Period = (SystemCoreClock / 17570) - 1
    The channel 1 and channel 1N duty cycle is set to 50%
    The channel 2 and channel 2N duty cycle is set to 37.5%
    The channel 3 and channel 3N duty cycle is set to 25%
    The channel 4 duty cycle is set to 12.5%
    The Timer pulse is calculated as follows:
     - ChannelxPulse = DutyCycle * (TIM1_Period - 1) / 100

    Note: 
    SystemCoreClock variable holds HCLK frequency and is defined in system_ys32f030.c file.
    Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
    function to update SystemCoreClock variable value. Otherwise, any configuration
    based on this variable will be incorrect. 
    ----------------------------------------------------------------------- */
    /* Compute the value to be set in ARR regiter to generate signal frequency at 17.57 Khz */
    TimerPeriod = (SystemCoreClock / PWM_CLK ) - 1;
    /* Compute CCR1 value to generate a duty cycle at 50% for channel 1 and 1N */
    Channel1Pulse = (uint16_t) (((uint32_t) 10 * (TimerPeriod - 1)) / 10);
    /* Compute CCR2 value to generate a duty cycle at 37.5%  for channel 2 and 2N */
//    Channel2Pulse = (uint16_t) (((uint32_t) 375 * (TimerPeriod - 1)) / 1000);
//    /* Compute CCR3 value to generate a duty cycle at 25%  for channel 3 and 3N */
//    Channel3Pulse = (uint16_t) (((uint32_t) 25 * (TimerPeriod - 1)) / 100);
//    /* Compute CCR4 value to generate a duty cycle at 12.5%  for channel 4 */
//    Channel4Pulse = (uint16_t) (((uint32_t) 125 * (TimerPeriod- 1)) / 1000);

    /* TIM1 clock enable */
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1 , ENABLE);
    TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
    /* Time Base configuration */
    TIM_TimeBaseStructure.TIM_Prescaler = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseStructure.TIM_Period = TimerPeriod;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;

    TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
    //TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
		
    /* Channel 1, 2,3 and 4 Configuration in PWM mode */
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;// TIM_OutputState_Enable;//TIM_OutputState_Disable;//TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_OutputNState =TIM_OutputNState_Enable;// TIM_OutputNState_Disable;// TIM_OutputNState_Disable;//  TIM_OutputNState_Enable;
    //TIM_OCInitStructure.TIM_Pulse =0;// Channel1Pulse;
    TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset;
    TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Reset;
		
		TIM_OCInitStructure.TIM_Pulse =0;//Channel1Pulse;
    TIM_OC1Init(TIM1, &TIM_OCInitStructure);
    TIM_OC1PolarityConfig(TIM1,TIM_OCPolarity_High );//TIM_OCPolarity_High TIM_OCPolarity_Low
    TIM_OC1NPolarityConfig(TIM1,TIM_OCNPolarity_High );//TIM_OCNPolarity_High  TIM_OCNPolarity_Low
		
    TIM_OCInitStructure.TIM_Pulse =0;//Channel1Pulse;
    TIM_OC2Init(TIM1, &TIM_OCInitStructure);
    TIM_OC2PolarityConfig(TIM1,TIM_OCPolarity_High );//TIM_OCPolarity_High TIM_OCPolarity_Low
    TIM_OC2NPolarityConfig(TIM1, TIM_OCNPolarity_High);//TIM_OCNPolarity_High

    TIM_OCInitStructure.TIM_Pulse =0;//Channel1Pulse;// Channel3Pulse;
    TIM_OC3Init(TIM1, &TIM_OCInitStructure);
    TIM_OC3PolarityConfig(TIM1, TIM_OCPolarity_High);
    TIM_OC3NPolarityConfig(TIM1,TIM_OCNPolarity_High );//TIM_OCNPolarity_High TIM_OCNPolarity_Low

//    TIM_OCInitStructure.TIM_Pulse =0;// Channel4Pulse;
//    TIM_OC4Init(TIM1, &TIM_OCInitStructure);
//    TIM_OC4PolarityConfig(TIM1, TIM_OCPolarity_Low); 
    //TIM_OC4NPolarityConfig(TIM3, TIM_OCNPolarity_High);		
    TIM_OCInitStructure.TIM_Pulse =64;//Channel1Pulse/16;// PWM_CYCLE_INIT/2;
    TIM_OC4Init(TIM1, &TIM_OCInitStructure);
		
    TIM_OC1FastConfig(TIM1, TIM_OCFast_Enable);
    TIM_OC2FastConfig(TIM1, TIM_OCFast_Enable);
    TIM_OC3FastConfig(TIM1, TIM_OCFast_Enable);
    TIM_OC4FastConfig(TIM1, TIM_OCFast_Enable);
    
    //CH1?CH2?CH3 Dead Time
    TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Enable;// TIM_OSSRState_Disable;//
    TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Enable;
    TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_OFF;
    TIM_BDTRInitStructure.TIM_DeadTime = 48;
    TIM_BDTRInitStructure.TIM_Break = TIM_Break_Disable;//TIM_Break_Disable;//TIM_Break_Enable;//
    TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_Low;//TIM_BreakPolarity_High;TIM_BreakPolarity_Low
    TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Disable;//TIM_AutomaticOutput_Enable;//TIM_AutomaticOutput_Disable;
    TIM_BDTRConfig(TIM1, &TIM_BDTRInitStructure);
		
		TIM1_NVIC_Configuration();
		TIM1->EGR |= TIM_EGR_CC4G;
    TIM_ITConfig(TIM1, TIM_IT_CC4, ENABLE);
    TIM_ITConfig(TIM1, TIM_IT_Update,ENABLE);
		TIM1->CR2 |= TIM_CR2_CCPC;
		TIM_Cmd(TIM1, DISABLE);
   // TIM_CtrlPWMOutputs(TIM1, ENABLE);		
    /* TIM1 counter enable */
//    TIM_Cmd(TIM1, ENABLE);
//		PWM_START();
//		PWM_SET_DUTY(Channel1Pulse);
////////    VH_ON
//////		VH_OFF
//////	
//////		UH_OFF 
//////	
//////		WH_OFF
//////    VH_ON
////		
//		PWM_AL_BH_ON()
//		PWM_AL_CH_ON()
//    PWM_BL_CH_ON()
//		PWM_BL_AH_ON()
//		PWM_CL_AH_ON()
//		PWM_CL_BH_ON()
//		PWM_AL_CH_ON()
//		stop_mos();
}

void TIM3_PwmCap_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
//	NVIC_InitTypeDef NVIC_InitStructure;
	TIM_ICInitTypeDef  TIM_ICInitStructure;

	//==========================================
	RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_GPIOB, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3 , ENABLE);

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_VeryHigh;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
	GPIO_Init(GPIOB, &GPIO_InitStructure);

	GPIO_PinAFConfig(GPIOB, GPIO_PinSource4, GPIO_AF_1);

	// =============================================

	TIM_TimeBaseStructure.TIM_Period = 0xffff;
	TIM_TimeBaseStructure.TIM_Prescaler = 47;//(MCU_SYSTEM_CLOCK/1000000)-1;
	TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

	TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
	TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
	TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
	TIM_ICInitStructure.TIM_ICFilter = 6;
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;

	TIM_PWMIConfig(TIM3, &TIM_ICInitStructure);

	TIM_SelectInputTrigger(TIM3, TIM_TS_TI1FP1);
	TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Reset);
	TIM_SelectMasterSlaveMode(TIM3,TIM_MasterSlaveMode_Enable);

	TIM3->SR=0;
	TIM3->DIER=(TIM_IT_CC1|TIM_IT_Update);

//	NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
//	NVIC_InitStructure.NVIC_IRQChannelPriority = 1;
//	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
//	NVIC_Init(&NVIC_InitStructure);

	TIM3->CR1|=TIM_CR1_CEN;
}


//*****************************************************************************//
static void PwmCap_SetDuty(uint16_t Cycle, uint16_t Duty)
{
  PwmCap_Duty = (PwmCap_DutyAvg+Duty)/2;
  PwmCap_DutyAvg = PwmCap_Duty;
  PwmCap_Cycle = (PwmCap_CycleAvg+Cycle)/2;
  PwmCap_CycleAvg = PwmCap_Cycle;
	TIM3->SR=0;
}
//*****************************************************************//
void PwmCap_IRQ(void)
{
	#if(M_Control_SET == 2)
	  if((TIM3->SR&TIM_IT_CC1) > 0)
	  {
		  PwmCap_SetDuty(TIM3->CCR1, TIM3->CCR2);
	  }
	  else if((TIM3->SR&TIM_IT_Update) > 0)
	  {
      if(GPIOB->IDR & GPIO_Pin_4)
        PwmCap_SetDuty(100, 100);
      else
        PwmCap_SetDuty(0, 0);
	 }
	 pwm_cap_process();
  #endif
	
}
/***************************************************
函数名称：pwm_cap_process
功能：    PwmCap_DutyAvg占空比，PwmCap_CycleAvg 是PWM周期时间
备注：    
****************************************************/
//*****************************************************8//
void pwm_cap_process(void)
{
	
	 if(AD_s.bat_flag)
		 return;
   if((PwmCap_DutyAvg>0)&&(PwmCap_CycleAvg>0))
	 {
	    if(m_par_set.Motor_state==M_INIT)
				 m_par_set.Motor_state=M_PRE_POS; 
			if(m_par_set.Motor_state==M_RUN)
			{   
			   m_par_set.actual_duty= PwmCap_DutyAvg*PWM_PERIOD/PwmCap_CycleAvg;
				 if(m_par_set.actual_duty<FSS_START_DUTY)
					  m_par_set.actual_duty=FSS_START_DUTY;
			}
	 
	 }
   if((PwmCap_DutyAvg==0)&&(PwmCap_CycleAvg==0))
	 {
	     m_par_set.Motor_state=M_STOP; 
	 }
}

