yahboom
HomeTutorialsProduct
Solution
Blog
Online Store
About Us
EN/中文
Store
STM32 Self-balancing Car📖
00.Get started quickly
  • 01.Balance car manual
  • 02.Balancing car assembly
  • 03.Get started quickly
  • 04.Balance car interface description
  • 05.Common Problem Analysis
  • 06.Balance Car V2 Library Function Development Manual
01.Environment development
  • 01.MDK-ARM installation
  • 02.STM32CubeIDE installation
  • 03.Common driver installation
  • 04.Download the program
  • 05.MDK-ARM project usage
  • 06.Program simulation
  • 07. VSCode Installation
02.STM32 getting started course
  • 01.Project creation
  • 02.LED Control(GPIO)
  • 03.Buzzer control(GPIO)
  • 04.Button control(EXTI)
  • 05.Serial communication(USART)
  • 06.Voltage detection(ADC)
  • 07.Basic timer(TIM)
  • 08.Universal timer(TIM)
  • 09.Advanced Timer(TIM)
  • 10.I2C Communication(I2C)-OLED
  • 11.SPI communication(SPI)-2.4G handle
  • 12.Independent Watchdog (IWDG)
  • 13.Window Watchdog (WWDG)
  • 14.DMA-USART
  • 15.DMA-I2C
03.STM32 expansion course
  • 01.Battery voltage detection (ADC)
  • 02.Ultrasonic module-measuring distance (TIM)
  • 03.Motor drive+encoder (TIM)
  • 04.OLED Data-Display(I2C)
  • 05.MPU6050-Data Read (I2C)
  • 06.Bluetooth module-Data reading (USART)
  • 07.2.4G handle-Data reading (SPI)
  • 08.Tracking module-Read status (GPIO)
  • 09.CCD module-Reading data (ADC)
  • 10.Electromagnetic module-Reading data (ADC)
  • 11.K210 module-Serial communication (USART)
  • 12.Tmini-Plus lidar-Reading data (USART)
04.Robot car PID control course
  • 01.PID basic concept
  • 02.PID example analysis
  • 03.P, PI, PD controller theory
  • 04.Position PID
  • 05.Incremental PID
  • 06.Cascade PID
  • 07.Balance principle of car
  • 08.Car upright control (PD)
  • 09.Car speed ​​control (PI)
  • 10.Car steering control (PD)
  • 11.Got angle and angular velocity (DMP algorithm)
  • 12.Got angle and angular velocity (Kalman filter algorithm)
  • 13.Got angle and angular velocity(Complementary filter algorithm)
05.Robot car basic course
  • 01.Car parameter adjustment
  • 02.Ultrasonic obstacle avoidance
  • 03.Ultrasonic follow
  • 04.Bluetooth remote control
  • 05.Load balance
06.Robot car advanced course
  • 01.4-channel tracking
  • 02.4-channel tracking avoid
  • 03.2.4G handle control
  • 04.CCD tracking
  • 05.CCD tracking avoid
  • 06.Electromagnetic tracking
  • 07.K210-QR code recognition
  • 08.K210-Color line tracking
  • 09.K210-Color follow
  • 10.K210-Self learning
  • 11.K210-Number recognition
  • 12.Lidar avoid
  • 13.Lidar guard
  • 14.Lidar follow
  • 15.Lidar patrol
  • 16.Lidar wall tracking-straight line
  • 17.Lidar wall tracking-multiple walls
  • 18. DIY Automatic driving car
07.Robot car LQR control
  • Robot car LQR control
08.Circuit design
  • 01.Overall circuit design
  • 02.STM32 minimum system
  • 03.Serial port circuit design
  • 04.Power circuit design
  • 05.MPU6050 Circuit Design
  • 06.Motor drive circuit design
09.Mathematical model
  • Mathematical model
10.Expand course
  • Autonomous Driving
Download
  • APP(Android)
  • Codes
  • Hardware-Info
  • SCH
  • Software Tools
  • STM32_Chip_DataSheet
  • 3D_Model_File
  • Video_PPT
Download ZIP

Welcome to STM32 Self-balancing Car repository

08.Universal timer(TIM)

Universal timer

Universal timerHardware connectionControl principlePin definitionSoftware codeControl functionExperimental phenomenon

The tutorial demonstrates the general timer (TIM3, TIM4) encoder interface mode to obtain the motor speed and print the motor speed through the serial port.

The tutorial only introduces the standard library project code

Hardware connection

image-20240825203903980

Since we have configured a special connection line, we only need to install it to the corresponding interface:

PeripheralsDevelopment BoardDescription
Motor 1: M+ (M1A)PC6The PC6 pin of the development board controls the input pin of the motor driver chip, and the output pin of the driver chip controls motor 1: M+
Motor 1: M- (M1B)PC7The PC7 pin of the development board controls the input pin of the motor driver chip, and the output pin of the driver chip controls motor 1: M-
Motor 1: Encoder VCC3.3VConnect the development board 3.3V to power the encoder
Motor 1: Encoder GNDGNDConnect the development board GND to the encoder common ground
Motor 1: Encoder A phase (H1A)PA7Encoder A of motor 1 is connected to pin PA7 of the development board
Motor 1: Encoder B phase (H1B)PA6Encoder B of motor 1 is connected to pin PA6 of the development board
Motor 2: M+ (M2A)PC8The PC8 pin of the development board controls the input pin of the motor driver chip, and the output pin of the driver chip controls motor 2: M+
Motor 2: M- (M2B)PC9The PC9 pin of the development board controls the input pin of the motor driver chip, and the output pin of the driver chip controls motor 2: M-
Motor 2: Encoder VCC3.3VConnect the development board 3.3V to power the encoder
Motor 2: Encoder GNDGNDConnect the development board GNDV to the encoder common ground
Motor 2: Encoder A phase (H2A)PB7Encoder A of motor 2 is connected to pin PB7 of the development board
Motor 2: Encoder B phase (H2B)PB6Encoder B of motor 2 is connected to pin PB6 of the development board

Control principle

Use the encoding interface mode of TIM3 and TIM4 of the general timer on the STM32F103RCT6 development board to count the encoder signal of the motor.

  • General purpose timer

Timer typeGeneral purpose timer
Timer nameTIM2, TIM3, TIM4, TIM5
Number of counter bits16
Counting modeIncremental/decremental/center-aligned
Prescaler factor1-65536
Generate DMA requestYes
Capture/compare channels4
Complementary outputNone
Clock frequency72MHz (maximum)
Mounting busAPB1
  • 520 motor

Motor model520 motor
Motor rated voltage12V
Encoder supply voltage3.3-5V
Gear set reduction ratio1:30
Number of magnetic ring lines11 lines
Encoder typeAB phase incremental Hall encoder

Count value

Maximumcountvalue=reductionratio∗encoderlinenumber∗4=30∗11∗4=1320
xxxxxxxxxx
4: represents encoder frequency multiplication
According to the count value of one rotation, the speed of the car can be calculated. This tutorial does not involve speed conversion
  • Encoder reading

Get the count value by directly reading the timer CNT register value.

image-20240903160750650

The tutorial sets counting on TI1 and TI2, sets the encoder mode to 4 times frequency, and the input signal is not reversed;

image-20240903160808875

xxxxxxxxxx
Whether the counter counts up or down depends on the AB phase signal

Pin definition

Main control chipPinMain function (after reset)Default multiplexing functionRedefine function
STM32F103RCT6PA6PA6SPI1_MISO/ ADC12_IN6/TIM3_CH1TIM1_BKIN
STM32F103RCT6PA7PA7SPI1_MOSI/ ADC12_IN7/TIM3_CH2TIM1_CH1N
STM32F103RCT6PB6PB6I2C1_SCL/TIM4_CH1USART1_TX
STM32F103RCT6PB7PB7I2C1_SDA/TIM4_CH2USART1_RX

Software code

Since the default function of the pin is the normal IO pin function, we need to use the multiplexing function.

xxxxxxxxxx
Product supporting materials source code path: Attachment → Source code summary → 1.Base_Course → 8.General_Timer

Control function

The tutorial only briefly introduces the code, you can open the project source code to read the details.

Encoder_Init_TIM3

​x
void Encoder_Init_TIM3(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    TIM_ICInitTypeDef TIM_ICInitStructure;
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //Enable timer 3 clock
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //Enable PA port clock

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7; //Port configuration
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //Floating input
    GPIO_Init(GPIOA, &GPIO_InitStructure); //Initialize GPIOA according to the set parameters

    TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
    TIM_TimeBaseStructure.TIM_Prescaler = 0; // Prescaler
    TIM_TimeBaseStructure.TIM_Period = ENCODER_TIM_PERIOD; //Set the counter auto-reload value
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //Select clock division: no division
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; /////TIM counts up
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
    TIM_EncoderInterfaceConfig(TIM3, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);//Use encoder mode 3
    TIM_ICStructInit(&TIM_ICInitStructure);
    TIM_ICInitStructure.TIM_ICFilter = 10; //Filter 10
    TIM_ICInit(TIM3, &TIM_ICInitStructure);
    TIM_ClearFlag(TIM3, TIM_FLAG_Update);//Clear TIM update flag
    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
    //Reset counter
    TIM_SetCounter(TIM3,0);
    TIM_Cmd(TIM3, ENABLE);
}

Encoder_Init_TIM4

xxxxxxxxxx
void Encoder_Init_TIM4(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    TIM_ICInitTypeDef TIM_ICInitStructure;
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); //Enable the clock of timer 4
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //Enable the clock of PB port

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7; //Port configuration
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //Floating input
    GPIO_Init(GPIOB, &GPIO_InitStructure); //Initialize GPIOB according to the set parameters
    TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
    TIM_TimeBaseStructure.TIM_Prescaler = 0x0; // Prescaler
    TIM_TimeBaseStructure.TIM_Period = ENCODER_TIM_PERIOD; // Set counter auto-reload value
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; // Select clock division: no division
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; /////TIM counts up
    TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
    TIM_EncoderInterfaceConfig(TIM4, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising); // Use encoder mode 3
    TIM_ICStructInit(&TIM_ICInitStructure); TIM_ICInitStructure.TIM_ICFilter = 10; TIM_ICInit(TIM4, &TIM_ICInitStructure); 
    TIM_ClearFlag(TIM4, TIM_FLAG_Update);//Clear the TIM update flag TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE); //Re set counter TIM_SetCounter(TIM4,0); TIM_Cmd(TIM4, ENABLE);
}

Read_Encoder

xxxxxxxxxx
int Read_Encoder(Motor_ID MYTIMX)
{
   int Encoder_TIM;    
   switch(MYTIMX)
     {
         case MOTOR_ID_ML:  Encoder_TIM= (short)TIM3 -> CNT;  TIM3 -> CNT=0;break;  
         case MOTOR_ID_MR:  Encoder_TIM= (short)TIM4 -> CNT;  TIM4 -> CNT=0;break;  
         default: Encoder_TIM=0;
     }
        return Encoder_TIM;
}

TIM3_IRQHandler

xxxxxxxxxx
void TIM3_IRQHandler(void)
{
    if(TIM3->SR&0X0001)// The overflow is interrupted
    {
    }
    TIM3->SR&=~(1<<0); // Clears the interrupt flag bit
}

TIM4_IRQHandler

xxxxxxxxxx
void TIM4_IRQHandler(void)
{
    if(TIM4->SR&0X0001)//Overflow interrupt
    {
    }
    TIM4->SR&=~(1<<0);//Clear interrupt flag
}

Experimental phenomenon

The General_Timer.hex file generated by the project compilation is located in the OBJ folder of the General_Timer project. Find the General_Timer.hex file corresponding to the project and use the FlyMcu software to download the program into the development board.

After the program is successfully downloaded: Use the serial port debugging assistant to see the encoder count information printed by the serial port.

xxxxxxxxxx
When using the serial port debugging assistant, you need to pay attention to the serial port settings. If the settings are wrong, the phenomenon may be inconsistent.

image-20240731152535808

Basic timer(TIM)
Advanced Timer(TIM)

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文