Skip to main content
Explorer II
September 9, 2023
Question

USING A GPIO PIN TO TAKE INPUT OF A PWM SIGNAL FOR MEASURING DUTY CYCLE AND FREQUENCY

  • September 9, 2023
  • 2 replies
  • 4029 views

I have a stm32g031k8 board. I was trying to give a pwm input signal like a square wave, measuring the frequency and duty cycle and generate pwm signal of that frequency and duty cycle using another timer. I was also changing the frequency and duty cycle of the input signal on the fly and it should change the output signal instantly. I was unable to do it. I was able to measure the frequency but nothing works. Please help me with the procedure. Thank You.

    This topic has been closed for replies.

    2 replies

    Graduate II
    September 9, 2023

    What Frequency are you attempting to measure.

    Should use the PWM Input modes, when CH1 captures period and CH2 the duty. Look for examples using the various boards that come in the CubeG0 package. Perhaps also review the TIM Cook Book

    Explorer II
    September 15, 2023

    I am giving an input frequency of 10 khz to like 500khz. I was using the timer 1 channel 1 for capturing the rising edge and channel 2 for capturing the falling edges. Then using the timer 2 I was trying to generate a PWM signal

    ST Employee
    September 11, 2023

    Hello @ritayandhara10

    You can refer to the TIM_PWMInput example to measure the duty cycle, period

    Since you're changing those parameters, you may want to use interrupts to capture the input signal edge and update PWM output signal

     

    Explorer II
    September 15, 2023

    I am giving an input frequency of 10 khz to like 500khz. I was using the timer 1 channel 1 for capturing the rising edge and channel 2 for capturing the falling edges. Then using the timer 2 I was trying to generate a PWM signal. 

    June 25, 2025


    Hi @ritayandhara10,

    To get real-time PWM tracking and generation working on your STM32G031K8, here’s a reliable method that works:

    Configure TIM1 in PWM Input Mode

    Use Channel 1 to capture the period (rising edge)

    Use Channel 2 to capture the high time (falling edge)

    Set TIM1 in slave reset mode so the counter resets on every rising edge

    Use Interrupts to Capture the Signal

    In the input capture callback, calculate:

    Period = value from CH1

    Duty = CH2 / CH1

    Frequency = system clock / period

    Call a function to update the output signal instantly

    Generate Output PWM with TIM2

    Set TIM2 ARR = period, CCR1 = high time

    Start PWM on TIM2 Channel 1

    This will recreate the input PWM signal with matched frequency and duty

    Ensure Both Timers Use the Same Clock

    Make sure TIM1 and TIM2 are running from the same clock domain (like APB or SYSCLK)

    Use interrupts for real-time reaction; polling won’t work well with changing signals

    This method handles 10 kHz to 500 kHz PWM inputs and updates the output smoothly.