STM8S: TIM5-PWM frequency and duty cycle measure.
I am trying to measure the frequency and duty cycle of a PWM input on TIM5 channel 1. My frequency is being measured correctly but the duty cycle is not.
GPIO_Init(GPIOD, GPIO_PIN_4, GPIO_MODE_IN_FL_NO_IT); //PWM input
I am using the 16MHz HSI clock with no Prescaler.
As detailed below, I am using channel 1 to capture the rising edge. I am using channel 2 to capture the falling edge from channel 1. Channel 2 triggers the interrupt.
TIM5_DeInit();
TIM5_TimeBaseInit(3, 65000); //Prescalar = 8 (2^3)->2MHz...Count up to 65,000 before resetting counter.
TIM5_CCxCmd(TIM5_CHANNEL_1, ENABLE);
TIM5_CCxCmd(TIM5_CHANNEL_2, ENABLE);
TIM5_PWMIConfig(TIM5_CHANNEL_1,
TIM5_ICPOLARITY_RISING,
TIM5_ICSELECTION_DIRECTTI,
TIM5_ICPSC_DIV1,
1);
TIM5_PWMIConfig(TIM5_CHANNEL_2,
TIM5_ICPOLARITY_FALLING,
TIM5_ICSELECTION_INDIRECTTI,
TIM5_ICPSC_DIV1,
1);
TIM5_ClearFlag(TIM5_FLAG_CC2);
TIM5_ITConfig(TIM5_IT_CC2, ENABLE);
TIM5_Cmd(ENABLE);
Interrupt Logic:
if(TIM5_GetFlagStatus(TIM5_FLAG_CC2))
{
rise_cnt=TIM5_GetCapture1();
fall_cnt=TIM5_GetCapture2();
TIM5_ClearITPendingBit(TIM5_IT_CC2);
TIM5_ClearITPendingBit(TIM5_IT_CC1);
}
Calculations: (I do take into account the 65,000 count up roll over.)
Period_**** = rise_cnt - prev_rise_cnt
Freq=2,000,000 / Period_****
Duty_Cycle = (fall_cnt-rise_cnt)/Period_****
What am I missing?
