# Generate a fixed number of pulses on the STM32F4 PWM

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?

• 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. Jun 5 '20 at 14:44
• Put a counter in the shortest possible interrupt routine? Jun 5 '20 at 14:44
• 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. Jun 5 '20 at 15:45
• @RonBeyer worst possible solution Jun 7 '20 at 10:00