STM32 Encoder Mode Explained: Read Rotary Encoders

In the previous article, STM32 Output Compare and One-Pulse Mode Explained, the timer used its capture/compare registers to produce events and pulses at exact counter values. Encoder mode goes back to the input side of the timer and uses the counter in a different way. Instead of counting ticks of an internal clock, the counter follows the two signals of a rotary encoder, so it moves up or down with every step of the shaft, and the timer does this without any work from the CPU.

A rotary encoder reports movement through two square-wave signals that are shifted against each other. It is possible to decode these signals in software with GPIO interrupts, as described in GPIO Interrupts and EXTI, but a fast shaft produces a large number of interrupts, and every missed edge becomes a permanent error in the position. The timer encoder interface avoids this problem, because the hardware samples both signals, decides the direction, and updates the counter on its own. In this article, we will first look at the signals of a quadrature encoder and at the way the timer decodes them. After that, we will wire an encoder to the board, configure the timer in CubeMX, and read the position and direction with the HAL library.

The examples use the NUCLEO-F446RE board with TIM3, where channel 1 is on pin PA6 and channel 2 is on pin PA7. TIM3 has a 16-bit counter on this device, which is convenient because the counter range is easy to reason about and to test. The encoder is the 360 Degree Rotary Encoder module (M274), a small mechanical encoder with 20 cycles per revolution that works from 3.3 V to 5 V. The same steps work for other encoders and other timers, and the places where an optical encoder behaves differently are pointed out along the way. This article is part of the STM32 timer tutorial series.

What Is a Quadrature Encoder

An incremental rotary encoder gives you pulses while the shaft turns, and nothing more. It cannot tell you the absolute angle at power-up. What it can tell you is how far the shaft has moved since you started counting, so the position always depends on a starting point that you define. Optical encoders do this with a slotted disc and a light sensor, magnetic ones use a magnet and a Hall sensor, and the knobs on control panels use sliding contacts. The electrical signals look the same in all three cases, which is why one timer setup works for all of them. The module in this article is the mechanical type, and its datasheet lists 20 cycles per revolution.

M274 360-degree rotary encoder module with knob and five pins

A quadrature encoder has two output channels, normally named A and B. While the shaft turns at a steady speed, each channel produces a square wave of the same frequency, and B is delayed by a quarter of a period compared with A. This delay is 90 electrical degrees, and the word quadrature refers to it.

Animation of an incremental encoder disc producing two square-wave signals, A and B, shifted by 90 degrees

The direction of rotation is hidden in that delay. When the shaft turns one way, A changes before B, and when it turns the other way, B changes before A. A single channel would give you the speed but not the direction, so the second channel is what makes the encoder useful. A quick way to see this is to look at B at the moment when A rises, because B is still low when A leads and already high when B leads.

The diagram below shows two full cycles for each direction, with a dashed line at every edge. If you count the dashed lines inside one cycle, you get four, and this number matters later when we talk about resolution.

Timing diagram of quadrature signals A and B: A leads B in one direction and B leads A in the other, with dashed lines at each edge

Signal States and Direction

Each edge of either channel moves the pair of signals into a new state, and only one of the two signals changes at a time. The table below lists the sequence of states for both directions, written as the level of A followed by the level of B.

DirectionState sequence (A, B)
A leads B00 โ†’ 10 โ†’ 11 โ†’ 01 โ†’ 00
B leads A00 โ†’ 01 โ†’ 11 โ†’ 10 โ†’ 00

Because only one signal changes per step, a decoder can tell the direction of every single step from the previous state and the new state. A jump of two signals at once is not a valid step, and it shows that an edge was missed or that the inputs are noisy. Many encoders also provide a third output called Z or index, which pulses once per revolution. Encoder mode does not use this channel, but it can be connected to a GPIO interrupt to detect a home position.


How STM32 Encoder Mode Works

The encoder interface is a feature of the timer peripheral, and it is available on general-purpose and advanced timers, but not on basic timers such as TIM6 and TIM7. These timer groups are compared in STM32 Timer Types Explained. The two encoder signals enter the timer on the channel 1 and channel 2 input pins, which are called TI1 and TI2 inside the timer. Each input passes through a digital filter and a polarity selection, and the cleaned signals then reach the encoder interface logic.

The encoder interface works as a slave mode of the timer, and it replaces the internal clock as the source that moves the counter. In the earlier articles, such as Prescaler, Counter and ARR Explained, the counter advanced on every tick of the timer clock. In encoder mode, the counter advances only when a valid edge arrives on the encoder inputs, and the direction logic decides whether the counter counts up or down. For this reason, the prescaler normally stays at 0, because a larger value would divide the encoder counts and lose steps.

Block diagram of the STM32 timer encoder interface: TI1 and TI2 inputs pass through filter and polarity into the encoder logic that drives the counter

Counter as Position Accumulator

In encoder mode, the counter register (CNT) works as an accumulator of encoder steps. It increases for every step in one direction and decreases for every step in the other direction, so its value always shows the net movement since the counter was last written. The value is not an angle by itself, because it is only a number of decoded steps, and a later section explains how to convert it to a workable value. The program can write any value into CNT at any time, for example to set the position to zero at a home switch.

The auto-reload register ARR defines the range of the counter. For a free-running position counter, ARR is set to the largest value that the timer supports, which is 65535 for a 16-bit timer and 4294967295 for a 32-bit timer. When the counter counts up beyond ARR, it wraps to 0, and when it counts down below 0, it wraps to ARR.


Decoding Resolution and Timer Support

The encoder interface offers more than one decoding resolution. In the mode that uses both channels, every edge of both signals moves the counter, so one full cycle of the encoder produces four counts, which is often called x4 decoding. The other modes count only the edges of one channel and use the level of the second channel for the direction, so one cycle produces two counts, which is called x2 decoding. The table below shows the three settings that the HAL library offers.

HAL settingEdges countedCounts per cycle
TIM_ENCODERMODE_TI12Both edges of both channels4
TIM_ENCODERMODE_TI1Both edges of one channel2
TIM_ENCODERMODE_TI2Both edges of the other channel2

Which timers and modes you get depends on the device. On the STM32F446, the encoder interface is available on TIM1 to TIM5 and on TIM8, where TIM2 and TIM5 have 32-bit counters and the others have 16-bit counters. Other families differ in the number of timers, the counter width, and the names of the modes, so look at the datasheet and at the timer chapter of the reference manual before you pick a timer. The timer clock and the input filter also set an upper limit for the encoder frequency, which only matters for fast optical encoders and not for a hand-turned knob.


Connect a Rotary Encoder to STM32 (Wiring and Pull-Ups)

The two encoder signals need to reach the channel 1 and channel 2 pins of the same timer, because the encoder interface reads them together as a pair. On the NUCLEO-F446RE, TIM3 can use PA6, PB4, or PC6 for channel 1 and PA7, PB5, or PC7 for channel 2. We use PA6 and PA7 here because they are free on the board and easy to reach on the Arduino header as D12 and D11. If you need a different pair, the alternate function table in the datasheet shows which pins each timer channel can use, and GPIO Alternate Functions Pins explains how to read that table.

The module has five pins, which are the supply(+), GND, CLK, DT, and SW. CLK and DT carry the A and B signals, and SW belongs to the push-button under the knob, which encoder mode does not use, so it stays unconnected. The product page gives an input voltage of 3.3 V to 5 V, so we power the module from the 3V3 pin of the Nucleo board and connect its GND to a GND pin of the board.

The next question is whether the signals need pull-up resistors, and the answer depends on how the encoder drives its outputs. The table covers the usual cases.

Encoder output typePull-up resistorsNotes
Mechanical contactsRequiredThe contacts only connect the pin to ground, so a pull-up creates the high level. This is the type of the module in this article.
Open-collector or open-drainRequiredThe output can only pull the line low, as explained in GPIO Push-Pull vs Open-Drain.
Push-pullNot neededThe output swings up to the encoder supply voltage, so that voltage must suit the pin.
Differential line driver (RS-422)Not applicableA line receiver converts each pair to a single-ended signal before it reaches the board.

Our module has mechanical contacts, so both signals need pull-ups. Modules of this kind usually carry the pull-up resistors on the board, which you can recognize as two small resistors near the pins, and the pull-ups then go to the supply pin.

Rotary encoder module board with the pull-up resistors for the CLK and DT lines highlighted

This is another reason to power the module from 3.3 V, because the signals then never exceed the level that the STM32 pins accept. If your board has no pull-ups, enable the internal ones in the GPIO settings as described in GPIO Pull-Up and Pull-Down Resistors. Enabling them on a board that already has pull-ups does no harm.

Pin connection table for the encoder module and NUCLEO-F446RE: 3V3, GND, CLK to PA6, DT to PA7
Wiring diagram connecting the rotary encoder module to the NUCLEO-F446RE using 3V3, GND, PA6 and PA7

Voltage Levels

Check the voltage before you connect anything. Our module accepts 3.3 V, so it connects without any extra parts, but many industrial encoders run from 5 V or from 12 V to 24 V, and a push-pull output then swings all the way up to that supply. Some STM32 pins tolerate 5 V, but only under the conditions given in the datasheet, and a 12 V or 24 V signal will damage any pin on the chip. The safe options are to power the encoder from 3.3 V when it supports that, to use an open-collector output with a pull-up to 3.3 V, or to put a level shifter or a line receiver between the encoder and the board.


Configure STM32 Encoder Mode in CubeMX

In this section, we configure TIM3 to decode the 600-cycle encoder with x4 resolution. If you have not used the tool before, STM32CubeMX Explained describes it in detail.

Select the Timer and Mode

Open Pinout & Configuration and select TIM3 under Timers. Set Combined Channels to Encoder Mode, which assigns the inputs for both channels in one step. On the STM32F446, CubeMX puts TIM3_CH1 and TIM3_CH2 on PA6 and PA7 by default, and you can move them to another valid pair by clicking the pin in the pinout view. After that, open the GPIO Settings tab and enable the internal pull-up on both pins if your encoder needs it.

STM32CubeMX pinout view with TIM3 Combined Channels set to Encoder Mode on pins PA6 and PA7

Set the Parameters

The parameters decide the counter range, the decoding resolution, and how the input signals are conditioned. Keep the prescaler at 0, and set the counter period to the full 16-bit range, so the counter only wraps at the ends of that range. The table lists the values used in this article.

ParameterValueReason
Prescaler (PSC)0The encoder edges clock the counter, so every edge counts once
Counter ModeUpEncoder mode changes the direction by itself
Counter Period (ARR)65535The full range of the 16-bit TIM3 counter
Encoder ModeTI1 and TI2Counts every edge of both channels, which gives x4 decoding
Polarity (CH1 and CH2)Rising EdgeThe signals are not inverted
IC Selection (CH1 and CH2)Direct TIEach input comes from its own pin
Input Filter (CH1 and CH2)15Rejects short glitches without limiting the speed in this example

The input filter makes a signal stay at a new level for a number of timer clock samples before the timer accepts the change. A higher value removes longer glitches, but it also delays every edge, which matters for fast encoders and does not matter for a knob that turns a few revolutions per second at most. At the 90 MHz timer clock used here, the highest value of 15 ignores glitches shorter than about 3 microseconds. Contact bounce in a mechanical encoder usually lasts much longer than that, so the filter only removes the shortest spikes. The quadrature decoding handles the rest in a natural way, because a contact that bounces back and forth counts one step up and then one step down, and the two cancel each other.

CubeMX TIM3 encoder parameters: prescaler 0, counter period 65535, TI1 and TI2 mode, input filter 15

After the code is generated, the function MX_TIM3_Init() contains the encoder configuration below.


Start the Encoder Interface

As with the other timer modes, the generated code prepares the peripheral but does not start it. The function HAL_TIM_Encoder_Start() switches on the counter and the input channels, and it takes the timer handle and a channel selection. Both channels take part in the decoding, so the selection has to be TIM_CHANNEL_ALL, because starting only one channel leaves the other input idle and the counter then misses half of the information.

HAL also provides HAL_TIM_Encoder_Start_IT() and HAL_TIM_Encoder_Start_DMA() for applications that need interrupts or DMA transfers. The plain version is enough for reading a position, since the counter keeps running in hardware and the program only reads it when it needs the value.


Read Encoder Position and Direction with HAL

Read the Counter

We read the current counter value with the macro __HAL_TIM_GET_COUNTER(), which returns the content of CNT. A single value says very little by itself, because the counter starts at 0 and wraps at the ends of its range. The useful information is the change between two readings. A positive change means that the shaft moved in the counting direction, a negative change means that it moved the other way, and a change of zero means that it did not move at all.


Handle Wraparound

The counter of TIM3 has 16 bits, so the reading jumps from 65535 to 0 when the shaft moves forward over the end of the range, and from 0 to 65535 when it moves backward over the start. A plain subtraction of two readings then gives a large wrong number at exactly these points. The fix is to subtract in the unsigned 16-bit type and to read the result as a signed 16-bit number, which gives the correct small change even when the counter wrapped between the two reads.

Diagram of the 16-bit encoder counter wrapping from 65535 to 0 while the signed difference still gives the correct step

The code below keeps the previous reading in a variable, calculates the signed change, and adds it to a position variable that is wider than the counter. Because this variable does not wrap at the counter limit, it can follow the shaft over many revolutions.

This method stays correct as long as the shaft moves less than half of the counter range between two reads, which is 32767 counts on a 16-bit timer. With the 80 counts per revolution of this encoder, that is more than 400 revolutions, so a hand-turned knob can never get close to the limit. Turning the knob through the wraparound point by hand would take about 800 revolutions, so for testing it is easier to start the counter close to the end of its range. The two lines below, placed after HAL_TIM_Encoder_Start(), start the counter at 65530, and a few clicks of the knob then carry it across the wrap while the position keeps counting correctly.

On a 32-bit timer such as TIM2 or TIM5, the same method works with the types uint32_t and int32_t. A different approach is to enable the update interrupt and count the overflow and underflow events, which is covered in STM32 Timer Interrupts Explained.


Read the Direction

The timer also remembers the direction of the last count in the DIR bit of the control register CR1. HAL gives the macro __HAL_TIM_IS_TIM_COUNTING_DOWN() to read it, and it returns a non-zero value when the last movement was downward. How such direction indicators work depends on the timer and on the device family, so check the reference manual before you rely on the bit. The sign of the calculated difference is the more portable choice, and it has the extra advantage of showing when nothing moved, which the direction bit cannot do.

The loop below reads the counter every 100 ms and sends the position, the number of clicks, the change, and the direction over the ST-LINK virtual COM port of the Nucleo board. It assumes that USART2 is enabled at 115200 baud, which is the default in the board preset. The click count is the position divided by 4, because the encoder in this article produces four counts (x4) for each click.

A slow UART transmission does not disturb the result, because the counter keeps running in hardware between the reads.


Test the Result

With the project running, open a serial terminal on the virtual COM port of the Nucleo board at 115200 baud. Any terminal program works, including the console view that is built into CubeIDE. The program prints one line every 100 ms, and while the knob stands still, every line shows a change of 0 and the direction STILL.

When we turn the knob by one click at a time, the position should change by 4, the click count by 1. Also the direction should read UP or DOWN depending on the movement.

The terminal output below shows the pattern that these steps produces.

Serial terminal showing pos, clicks, delta and dir values, with a delta of 4 counts per click

Every line with movement shows a change of exactly 4 counts, which confirms that one click of this encoder produces four counts in x4 mode. The click count follows the position in steps of one, and it becomes negative when the knob is turned below the starting point. The lines with a change of 0 and the direction STILL appear while the knob stands still, and the position returns to exactly 0 at the end, which shows that no counts were lost or added along the way. When the knob moves while the loop samples the counter, a single click can be split over two lines, for example a change of 1 followed by a change of 3, but the total stays the same.


Convert Encoder Counts to Angle and Distance

A counter value turns into an angle only when we know how many counts one revolution produces. That number comes from two places, the encoder datasheet and the decoding mode we configured. Datasheets usually give the resolution as pulses per revolution (PPR) or cycles per revolution (CPR), which is the number of full cycles that one channel produces in one turn of the shaft. One cycle contains two edges on each channel, so the two channels together produce four edges per cycle, and the configured mode decides how many of them the counter uses. In x4 mode, the counts per revolution are four times the CPR value, and in x2 mode they are two times that value.

The table lists the assumptions of the example project. If you use a different encoder, change the first two rows, and the other values follow from them.

ItemValue
Encoder resolution20 cycles per revolution (CPR)
Decoding modeTI1 and TI2 (x4)
Counts per revolution80
Angle per count4.5ยฐ
Counts per click (detent)4
Gearbox between encoder and loadNone (1:1)
Timer and counter widthTIM3, 16 bit (ARR = 65535)
Counter wraps afterabout 819 revolutions

With these values, the shaft angle in degrees is the position multiplied by 360 and divided by 80. This is a coarse resolution, because each count is already 4.5ยฐ. The encoder is a good fit for a knob that selects values or moves a menu, but not for precise positioning. When an encoder with a higher resolution or a gearbox is used, the same formula applies with the larger count. If an encoder with 80 counts per revolution sits on a motor shaft that drives a 30:1 gearbox, the counts per revolution of the output shaft are 80 ร— 30 = 2400, so each count is only 0.15ยฐ.

To see the angle in the terminal, calculate it in the main loop and add it to the message that the example loop sends. The line below replaces the snprintf call from the previous section, and the click count is left out here to keep the output short.

Printing a float with snprintf needs one extra setting in CubeIDE. Open the project properties, go to C/C++ Build โ†’ Settings โ†’ MCU Settings, and enable Use float with printf from newlib-nano. Without this option, the angle is printed as an empty value.

With 80 counts per revolution, one click moves the angle by 18ยฐ, ten clicks give half a turn, and twenty clicks give a full turn. The terminal output below shows what the loop should print when the knob is turned in one direction, with the position and the matching angle on each line.

Serial terminal showing encoder position and angle, with each click adding 18 degrees

Each click of four counts adds 18ยฐ to the angle, so the knob reads 90ยฐ after five clicks and 126ยฐ after seven. The repeated lines appear because the loop prints every 100 ms, and the knob did not move between some of the prints. The line with a position of 17 shows the knob resting one count past a click, and its angle of 76.5ยฐ is exactly 17 ร— 4.5ยฐ, which makes the resolution of a single count visible. If you want a value between 0ยฐ and 360ยฐ instead, take the position modulo 80 before the conversion, for example with ((position % 80) + 80) % 80, which also gives a correct positive result when the knob turns backward.

A distance works the same way, using the travel of the mechanism per revolution. For a wheel, this travel is the circumference, which is ฯ€ times the diameter. A wheel with a diameter of 60 mm moves about 188.5 mm per revolution, so with 80 counts per revolution, one count is roughly 2.36 mm. The speed comes from the change in counts over a fixed time interval, and in revolutions per minute it equals the change multiplied by 60 and divided by the product of the counts per revolution and the interval in seconds. A timer interrupt with a fixed period gives you a precise interval for this calculation.


Common STM32 Encoder Problems and Fixes

Swapped A and B Channels

When the position goes down although you turn the shaft in the direction that should increase it, the two channels are most likely swapped. The simplest fix is to exchange the wires of CLK and DT. Inverting the polarity of one channel in the CubeMX encoder settings also reverses the counting direction, and so does multiplying the calculated difference by -1 in the code. Which direction counts up depends on the wiring, the polarity, and the way the encoder is mounted, so turn the shaft by hand once and check what the counter does.


Wrong Counts-per-Revolution Assumption

The most common mistake in the conversion is to use the CPR value from the datasheet as the counts per revolution. In x4 mode, the counter advances four times per cycle, so a 20-cycle encoder produces 80 counts, and a wrong divisor makes every angle four times too large. A reliable check is to mark the shaft, turn it exactly one revolution, and read the change of the counter. A result of 80 confirms x4 decoding, a result of 40 shows that only two edges per cycle are counted, and any other number points to a different resolution than the one you assumed. Mechanical encoders add another source of confusion, because they usually produce four counts per click in x4 mode, so a menu that should move one step per click has to divide the count by four, as the example loop does.


Contact Bounce and Floating Inputs

The contacts of a mechanical encoder do not switch cleanly, and the signal can flicker for a short time around every edge. The timer filter and the cancelling effect of the quadrature decoding absorb most of this, and a small capacitor on each signal pin helps when the position still drifts. A floating input is a different problem that looks similar, because an input without a pull-up picks up noise and produces counts while the knob stands still. Both pins need a defined level, which comes from the pull-ups on the module or from the internal pull-ups of the STM32, and the wires should be short and kept away from motor cables.


Wraparound and Mechanical Backlash

A counter wraparound is not an error, and the signed difference method from the previous section handles it correctly as long as the counter is read often enough. Backlash is a different matter, because it is a mechanical effect that the encoder cannot see. A knob does not have this problem, but an encoder on a motor shaft does, because the gears have a small amount of play, so after a direction change the encoder keeps counting while the output shaft has not started to move yet. Mounting the encoder on the output shaft removes this effect, and if that is not possible, a software compensation or a fixed approach direction for precise positioning reduces it.


Conclusion

Encoder mode turns a timer into a hardware decoder for quadrature encoders. The two signals enter through the channel 1 and channel 2 inputs, the encoder interface works out the direction, and the counter moves on every valid edge. The counter then holds the net movement of the shaft, and your program only has to read it when it needs the position.

For reliable results, pick a timer that supports encoder mode, check that the signal levels suit the pins, and match the pull-ups and the filter to the type of encoder. In the code, use the signed difference between two readings to follow the position across counter wraparound, and use the real counts per revolution of the chosen decoding mode for every conversion. In the next articles of the timer series, we will look at more timer features that build on the same counter and channel logic.


Download the Project Here

Download the CubeMX project files and HAL source code โ€” all tested on real hardware.

If you find this useful, you can support us with a Donation as well.

What to Read Next

Article by Yashmiti

Yashmiti is a technical writer at STM32Guide, where she creates tutorials and guides that help embedded-systems learners and developers work confidently with STM32 microcontrollers. Her writing covers tools like STM32CubeIDE and STM32CubeMX, along with peripherals and communication protocols โ€” always with an emphasis on clear explanations and hands-on examples that take readers from concept to working project.

She's also part of the effort to build STM32Guide into an organized, easy-to-navigate resource for the STM32 community.

Leave a Comment