Library 26- Rotary encoder on STM32F4

A rotary encoder, also called a shaft encoder is an electro-mechanical device than converts the angular position or motion of a shaft to an analog or digital. There are 2 types of rotary encoders:

  • Incremental – output indicates just rotation clockwise or counterclockwise
  • Absolute – output indicates current position for encoder

For that purpose I made a one simple library. This library works for incremental rotary encoders. It uses an interrupt to handle rotations. On the rotary encoders inside are basically 2 pushbuttons. And because they are mehanical, you can also expect some debouncing. STM32F4 is a fast device and will handle this debouncing what you don’t want. For that you have to make a good filtering. I made a schematic. how to properly connect rotary encoder to STM32F4 to disable debouncing effect.

Properly connected rotary encoder to STM32F4 device

Properly connected rotary encoder to STM32F4 device



  • Operate with up to 16 rotary encoders at a time.
  • External interrupt based detection, not TIM’s input.
  • Version 2.0 – March 22, 2015
    • Library rewritten to support up to 16 rotary encoders
    • It is not compatible with older versions


    • STM32F4xx
    • STM32F4xx RCC
    • STM32F4xx GPIO
    • STM32F4xx EXTI
    • STM32F4xx SYSCFG
    • MISC
  • TM
    • defines.h
    • TM EXTI
    • TM GPIO

Rotary encoder has 3 pins. pins A, B and C (common). My library uses only A pin to be connected to interrupt, B can be whatever else.

You set your pins when you initialize your custom rotary encoder. And, if you need, you can use up to 16 rotary encoders. This number depends on EXTI feature. It supports 16 interrupt lines at a time, because rotary encoder uses one pin (typically pin A) for interrupt source.




Rotary encoder result

Rotary encoder result

This example uses default settings, PD0 and PD1 are in use.

View project on Github, download library below.


Owner of this site. Application engineer, currently employed by STMicroelectronics. Exploring latest technologies and owner of different libraries posted on Github.

You may also like...