Skip to main content
Visitor II
September 13, 2021
Question

STM8S: TIM5-PWM frequency and duty cycle measure.

  • September 13, 2021
  • 3 replies
  • 1407 views

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?

    This topic has been closed for replies.

    3 replies

    Technical Moderator
    September 14, 2021

    Welcome, @JRing.2​, to the community!

    TIM5 does not overflow at 65000, but at 2^16 = 65536, i.e. counts from 0 ... 65535.

    Regards

    /Peter

    JRing.2Author
    Visitor II
    September 14, 2021

    TIM5_TimeBaseInit(3, 65000); sets my auto-reload register which causes the counter to roll over at 65000. Even if I change it to 2^16, my duty cycle capture is not functioning correctly.

    Technical Moderator
    September 14, 2021

    What does "not functioning correctly" mean exactly?

    JRing.2Author
    Visitor II
    September 14, 2021

    I am sending it a PWM signal 2KHz, 70% duty cycle. I confirm this with an oscilloscope. With the above settings, I measure a rising edge every 1000 counts, as I should. I should be getting a falling edge 700 counts after that. Instead, the falling edge is captured at 200.