Using PWM timers to control stepper motors

Hello to everybody,

I am investiganting the use of Arduino internal timers to control a stepper motor, and I am thinking of writing a new library exploiting this functionality. The stepper motors that I am using require two signals: clock and direction. The direction pin is trivial, while the clock pin can be more difficult. In my vision, there are two paths that can be followed:

For the first approach, I found the AccelStepper library that I think uses internal functions, as micros() or millis(), to control steps timing. As stated in the library page the maximum velocity is 4 kHz.

For the second approach, I would like to get to higher speeds using the ATMega internal timers that control PWM pins. I found this very good review about the Secrets of Arduino PWM that teaches about a low level control of the timers. Quoting the guide:

Each of the timers has a prescaler that generates the timer clock by dividing the system clock by a prescale factor such as 1, 8, 64, 256, or 1024. The Arduino has a system clock of 16MHz and the timer clock frequency will be the system clock frequency divided by the prescale factor.

This is very interesting, indeed.

Ending this short review, let us start with the questions. Using the PWM frequency I am not aware if there is a way to count the emitted pulses. Are there any? Since there are three timers (See pp. 94, 113 and 144 of the datasheet), up to three stepper motors can be controlled simultaneously. But if there are no ways to count the steps via software, one of the timers could be used as a counter and it seems that the Timer/Counter2 can be used for that (See p. 144 of the datasheet). I am not an expert on microcontrollers so I am not sure about this, plus I do not know how to implement a counter with the Timer/Counter2. Also, controlling the PWM output frequencies, speed ramps could be developed.

I hope that this post, and its short review on the topic, can be usefull to anybody that is looking for help.

Cheers

Using the PWM frequency I am not aware if there is a way to count the emitted pulses. Are there any?

Yes,
You get the timer to generate a "Output Compare Match Interrupt Enable" and have the ISR count the number of times it is entered.