STM32F411 Timer Encoder Mode for Micromouse - Quadrature Encoder, Encoder Mode Works, Encoder Channels, Position and Speed Measurement, STM32 HAL Library, Encoder Overflow

 

STM32F411 Timer Encoder Mode for Micromouse - Quadrature Encoder, Encoder Mode Works, Encoder Channels, Position and Speed Measurement, STM32 HAL Library, Encoder Overflow

Encoder mode is one of the most useful timer features in the STMicroelectronics STM32F411 microcontroller. It allows the timer hardware to directly interface with a quadrature encoder without requiring heavy CPU processing.

This feature is widely used in:

  • Robotics
  • Micromouse robots
  • CNC machines
  • Servo motor systems
  • Industrial automation
  • Position control systems

Encoder mode provides accurate position and speed measurement for rotating motors and shafts.


What Is a Quadrature Encoder?

A quadrature encoder is a rotary sensor that generates two digital output signals:

  • Channel A
  • Channel B

These signals are shifted by 90 degrees in phase.

Typical encoder outputs look like this:

MicromouseEncoderSignal

By analyzing the phase difference between Channel A and Channel B, the STM32F411 timer can determine:

  • Rotation direction
  • Position
  • Speed
  • Number of pulses


How Encoder Mode Works

In encoder mode, the timer counter increases or decreases automatically based on encoder signals.

MicromouseEncoderSignalValue

Normally, timers count internal clock pulses.

In encoder mode:

  • External encoder signals become the clock source
  • Timer counter changes according to shaft movement
  • The hardware automatically handles:
    • Edge detection
    • Direction detection
    • Pulse counting
This greatly reduces CPU overhead.


Encoder Channels

Encoder mode uses two timer input channels:

Encoder SignalTimer Input
Channel ATIMx_CH1
Channel BTIMx_CH2

For example:

  • TIM2_CH1 → PA0
  • TIM2_CH2 → PA1

The timer continuously monitors both signals.


Direction Detection

The phase relationship between Channel A and Channel B determines direction.

Clockwise Rotation
  If Channel A leads Channel B: Counter increments

Counter-Clockwise Rotation
 If Channel B leads Channel A: Counter decrements

This happens automatically inside the timer hardware.


Encoder Counting Modes

STM32F411 timers support multiple encoder modes.

  • Mode 1 : Counter changes based on TI1 edges only
  • Mode 2 : Counter changes based on TI2 edges only
  • Mode 3 : Counter changes using both TI1 and TI2 edges

Mode 3 provides the highest resolution.


Encoder Resolution

Encoder resolution determines how many counts are generated per mechanical revolution.

Example:

   Encoder = 500 PPR (Pulses Per Revolution)

   Using x4 decoding:

   Result:

Counts=4×500=2000Counts = 4 \times 500 = 2000   This means:
      One revolution = 2000 timer counts

Higher resolution improves positioning accuracy.


Timer Counter Operation

The timer counter register (CNT) stores encoder position.

As the shaft rotates:

  • CNT increases
  • CNT decreases

Example:

  • Initial position = 0
  • Rotate forward → CNT = 150
  • Rotate backward → CNT = 90

The counter behaves like a digital position tracker.


Position Measurement

Encoder mode enables accurate angular position measurement.

The angle equation is:

θ=CountCounts Per Revolution×360\theta=\frac{Count}{Counts\ Per\ Revolution}\times360^\circ

Example:

  • Current count = 500
  • CPR = 2000

Result:

θ=5002000×360=90\theta=\frac{500}{2000}\times360=90^\circ

The motor shaft is rotated 90 degrees.


Speed Measurement

Motor speed can be calculated by measuring count changes over time.

RPM equation:

RPM=ΔCount×60CPR×ΔtRPM=\frac{\Delta Count\times60}{CPR\times\Delta t}

Where:

  • ΔCount = count difference
  • CPR = counts per revolution
  • Δt = elapsed time

This method is widely used in motor controllers and robotics.


Hardware Configuration

Step 1 — Enable Timer Clock

  The timer peripheral clock must be enabled.
  Example:

  • Enable TIM2 clock
  • Enable GPIO clock

Step 2 — Configure GPIO Pins

  Encoder pins must use:
  • Alternate function mode
  • Pull-up resistors
  • Proper timer alternate function mapping
  Example:
  • PA0 → TIM2_CH1
  • PA1 → TIM2_CH2

Step 3 — Configure Timer Encoder Mode

  Important settings:
  • Encoder interface mode
  • Input polarity
  • Prescaler
  • Auto-reload value
  Common configuration:
  • Mode = TIM_ENCODERMODE_TI12
  • Prescaler = 0
  • ARR = 4294967295

Step 4 — Start Encoder Interface

After initialization:
  • Start timer encoder mode
  • Read CNT register continuously
The hardware immediately begins tracking movement.

Real coding for Initialize :

/* TIM2 init function */

void MX_TIM2_Init(void)

{


/* USER CODE BEGIN TIM2_Init 0 */


/* USER CODE END TIM2_Init 0 */


TIM_Encoder_InitTypeDef sConfig = {0};

TIM_MasterConfigTypeDef sMasterConfig = {0};


/* USER CODE BEGIN TIM2_Init 1 */


/* USER CODE END TIM2_Init 1 */

htim2.Instance = TIM2;

htim2.Init.Prescaler = 0;

htim2.Init.CounterMode = TIM_COUNTERMODE_UP;

htim2.Init.Period = 4294967295;

htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;

htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;

sConfig.EncoderMode = TIM_ENCODERMODE_TI12;

sConfig.IC1Polarity = TIM_ICPOLARITY_RISING;

sConfig.IC1Selection = TIM_ICSELECTION_DIRECTTI;

sConfig.IC1Prescaler = TIM_ICPSC_DIV1;

sConfig.IC1Filter = 0;

sConfig.IC2Polarity = TIM_ICPOLARITY_RISING;

sConfig.IC2Selection = TIM_ICSELECTION_DIRECTTI;

sConfig.IC2Prescaler = TIM_ICPSC_DIV1;

sConfig.IC2Filter = 0;

if (HAL_TIM_Encoder_Init(&htim2, &sConfig) != HAL_OK)

{

Error_Handler();

}

sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;

sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;

if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)

{

Error_Handler();

}

/* USER CODE BEGIN TIM2_Init 2 */

HAL_TIM_Base_Start(&htim2);

HAL_TIM_Encoder_Start(&htim2, TIM_CHANNEL_ALL);

// TIM2->DIER |= TIM_DIER_UIE;

/* USER CODE END TIM2_Init 2 */


}


Using STM32 HAL Library

The STM32 HAL library simplifies encoder configuration.

Typical initialization functions:

  • HAL_TIM_Encoder_Init()
  • HAL_TIM_Encoder_Start()

Reading position:

  • __HAL_TIM_GET_COUNTER()

This makes encoder applications easier for beginners.


Encoder Noise and Signal Quality

Real encoders may produce noisy signals.

Common solutions:

  • Digital filtering
  • Shielded cables
  • Pull-up resistors
  • Hardware debounce

STM32 timers include built-in input filtering for cleaner measurements.


Encoder Overflow Problem

The timer counter has limited size.

Example:

  • 16-bit timer maximum = 65535

If the encoder rotates continuously:

  • Counter eventually overflows

Solutions:

  • Use software overflow tracking
  • Use 32-bit timers like TIM2 or TIM5

TIM2 is especially useful because it supports 32-bit counting.


Advantages of STM32 Encoder Mode

Hardware-Based Processing
  • Minimal CPU usage because counting is handled by hardware.
High Accuracy
  • Precise pulse detection improves positioning.
Real-Time Performance
  • Immediate response to encoder movement.
Direction Detection
  • Automatic forward and reverse tracking.
Easy Integration
  • Works directly with most incremental rotary encoders.

Conclusion

STM32F411 timer encoder mode is a powerful hardware feature for motion tracking and motor control. It allows direct interfacing with quadrature encoders while minimizing CPU load. By automatically detecting direction and counting pulses, the timer provides accurate position and speed information for robotics, automation, and embedded control systems.

For applications such as Micromouse robots, CNC systems, and motor controllers, encoder mode is one of the most important capabilities of the STM32F411 microcontroller.

Comments

Popular posts from this blog

How to Build a Micromouse Robot - Mechanical, Hardware, Software

Micromouse Competitions - Types, Overview, Comparison, Advantages, Worldwide

Complete Guide to Micromouse Maze - Dimensions, Structure and Components, Building