Electrical – How to count the number of the generated PWM pulse on stm32

microcontrollerpwmstm32stm32f4timer

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?

Best Answer

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 to TIM2. TIM5 would be a good choice as it has a 32 bit counter.
  • Set TIM2 as master, trigger output on Update (MMS bits in CR2). It will generate a trigger output whenever the PWM counter is reloaded.
  • Set TIM5 as slave. First, check the table at the end of the SMCR register description. Find TIM2_TRGO (the master) in the row corresponding to TIM5 (the slave). Note the TS=xxx setting in the column header, this value goes into the TS bits of SMCR. Slave Mode (SMS) should be External Clock Mode (111 = 0x07). Now, TIM5 will count the reloads of TIM2, effectively the PWM cycles.
  • Enable the slave (TIM5) first, the master (TIM2) afterwards.