I have a stepper motor on TIM2 CH1. When a button is pressed the motor runs. How to count the steps(pulse) the PWM generated while the button was pressed?
1 Answer
\$\begingroup\$
\$\endgroup\$
Use another timer as a slave to count TIM2
reloads.
- Pick a second timer as a slave. Check the description of the
SMCR
register in the Reference Manual to see if it can be slaved toTIM2
.TIM5
would be a good choice as it has a 32 bit counter. - Set
TIM2
as master, trigger output on Update (MMS
bits inCR2
). It will generate a trigger output whenever the PWM counter is reloaded. - Set
TIM5
as slave. First, check the table at the end of theSMCR
register description. FindTIM2_TRGO
(the master) in the row corresponding toTIM5
(the slave). Note theTS=xxx
setting in the column header, this value goes into theTS
bits ofSMCR
. Slave Mode (SMS
) should be External Clock Mode (111
=0x07
). Now,TIM5
will count the reloads ofTIM2
, effectively the PWM cycles. - Enable the slave (
TIM5
) first, the master (TIM2
) afterwards.