Encoder speed measurement [STM32 Nucleo]

The STM32 timer has the ability to measure external pulses. Encoders are often used as sensors to detect the position and speed of actuators such as robots, etc. This section introduces a method to measure pulses that vary with rotation speed from encoders.

Pulse rate is the number of counts per unit of time, so it is sufficient to use a function that can count external pulses.

The encoder used in this application is an open collector output type specification. The open collector output is a type in which the collector of the transistor is the output terminal, and the collector and emitter are also open non-voltage contacts. To connect to a microcontroller, pull up the collector side and set the emitter side to GND.

Open collector output MCU connection

To measure (count) encoder pulses with the STM32, connect them as inputs to a peripheral timer. As shown in the connection example below, only one of the two phases of the encoder output is used to measure speed; to use the STM32's external pulse measurement function, only CH1 and CH2 of the timer can be used.

Connection diagram of encoder speed measurement

The following is an explanation of the settings in the actual program.

Purpose: To count encoder pulses pulled up and input to CH1 of TIM3 every unit time.
■ Use channel CH1 (PA6) of timer TIM3 set as pull-up input
■ Set to External clock mode to up-count
■ Get a count value and then reset the count every fixed period(useful with RTOS).

 Initialization of GPIO and Timer TIM3 

 In the GPIO setup, the encoder's open collector output is connected to a pull-up to CH1 of TIM3.
In the TIM3 setting, set the count to up-count, and set TIM.Period to a value that does not overflow the count value.

Use TIM_TIxExternalClockConfig() to set the external clock mode. For details on how to use this function, see "Timer Applications" section in "Timer/Counter[STM32 Timers Details]".

 Get count value every unit of time 

Use TIM_GetCounter(TIMx) to get the count value. The argument specifies the timer to be set, such as TIM3.

This application example uses an RTOS to obtain a count value every 100 ms before resetting. The pulse speed is monitored as a pulse speed value via serial communication, and the pulse speed is converted per second. If the encoder has a resolution of 180 p/r, it is successful if the pulse speed value is 180 when it is rotated at a speed of exactly one revolution per second.

Once the speed of the encoder is known, it becomes a little more advanced, but the feedback allows for exact speed control. This is the basis of motion control, so give it a try.

For detail on how to use The encoder high-speed pulse counter in the STM32, see "Timer Application"-"External High-Speed Clock Counting" - External Clock Mode in "Timer/Counter[STM32 Timers Details]".

Follow me!