I am trying to control a servo motor (link). It is a brushless DC motor with an interface similar to a stepper motor.

The motor rotates for a defined distance based on the number of pulses it receives from the PWM. The speed is determined by the pulse frequency of the PWM, like a stepper motor.

To control this motor I am using a microcontroller STM32F407ZET6. I can easily change the frequency and Duty Cycle of PWM, but my question is the following:

How do I generate a fixed number of pulses in the PWM? For example, I want the PWM to send 1000 pulses at a certain time with a frequency of 20kHz and a Duty Cycle of 50%. 20kHz and 50% Duty Cycle are easy to define, but I can't determine how to generate the 1000 fixed pulses.

One of the solutions I tried was to connect the PWM back to a timer in counter mode and stop the PWM when the required number of pulses has been generated. But the number of pulses is not always fixed, sometimes ranging from 998 to 1005 (for example).

Is it possible to do this without the need for feedback?

  • \$\begingroup\$ If you want a specific number of pulses you may have to bit-bang your PWM using a timer and not the built-in PWM generator. \$\endgroup\$
    – Ron Beyer
    Commented Jun 5, 2020 at 14:44
  • 2
    \$\begingroup\$ Put a counter in the shortest possible interrupt routine? \$\endgroup\$
    – user16324
    Commented Jun 5, 2020 at 14:44
  • \$\begingroup\$ If the pulse count is known, you know how much time it takes to send them, and you can use another timer to disable the PWM. \$\endgroup\$
    – Justme
    Commented Jun 5, 2020 at 15:45
  • \$\begingroup\$ @RonBeyer worst possible solution \$\endgroup\$ Commented Jun 7, 2020 at 10:00

1 Answer 1


Enable capture compare interrupt with setting CCxIE bit in TIMx_DIER register(fill x's with your timer and cc channel). this enables an interrupt processed whenever a pulse is completed. In your isr you can check TIMx_CNT register to double check.

Enable pwm, start counting your pulses in isr, when you reach the desired number of pulse disable pwm.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.