这一篇来介绍STM32的定时器,STM32的定时器分为三类:
- 基本定时器(Basic timers):从0计数到预设的值,并触发中断或DMA,没有其它功能,其内部与DAC相连,可以用于触发DAC;
- 通用定时器(General-purpose timers):可以升序或者降序计数,可以用于输入捕捉、PWM输入、比较输出、PWM输出、单脉冲输出等等功能;
- 高级定时器(Advanced-control timers):拥有基本定时器和通用定时器的全部功能,并有输出PWM中插入死区、编码器解码以及三相6步电机驱动功能。
对于STM32F103C8T6来说,用于3个通用定时器和1个高级定时器(手册中)。这一篇使用通用定时器来输出不同占空比的PWM波控制LED,达到呼吸灯的效果。
原理设计
在系统板上,PB8用于控制LED,查阅STM32F103C8T6手册,可知PB8为定时器4的第3通道输出引脚:
因此需要对定时器4进行分析。
TIM4定时器
定时器时钟
定时器4为STM32的通用定时器,其内部结构如图所示:
上面为定时器的时钟信号选择部分,在第2篇中分析过,定时器挂载在APB1总线上,而APB1时钟信号在SystemInit()函数初始化后为36MHz,然后经过APB1总线的一个倍频器,在初始化后这个倍频器使APB1时钟信号2倍频后进入定时器;
也就是说,虽然APB1总线上的时钟信号为36MHz,但由于这个2倍频器,最终进入定时器的时钟信号为72MHz,也就是上图中CK_PSC时钟信号为72MHz。
CK_PSC时钟信号经过PSC Prescaler分频后,进入计数器,作为计数器的时钟信号。
定时器库函数
基础初始化结构体TIM_TimeBaseInitTypeDef
和其它外设初始化一样,定时器初始化也有其初始化结构体,可以对照函数手册进行分析,这里直接贴上代码:
/**
* @brief TIM Time Base Init structure definition
* @note This structure is used with all TIMx except for TIM6 and TIM7.
*/
typedef struct
{
uint16_t TIM_Prescaler; /*!< Specifies the prescaler value used to divide the TIM clock.
This parameter can be a number between 0x0000 and 0xFFFF */
uint16_t TIM_CounterMode; /*!< Specifies the counter mode.
This parameter can be a value of @ref TIM_Counter_Mode */
uint16_t TIM_Period; /*!< Specifies the period value to be loaded into the active
Auto-Reload Register at the next update event.
This parameter must be a number between 0x0000 and 0xFFFF. */
uint16_t TIM_ClockDivision; /*!< Specifies the clock division.
This parameter can be a value of @ref TIM_Clock_Division_CKD */
uint8_t TIM_RepetitionCounter; /*!< Specifies the repetition counter value. Each time the RCR downcounter
reaches zero, an update event is generated and counting restarts
from the RCR value (N).
This means in PWM mode that (N+1) corresponds to:
- the number of PWM periods in edge-aligned mode
- the number of half PWM period in center-aligned mode
This parameter must be a number between 0x00 and 0xFF.
@note This parameter is valid only for TIM1 and TIM8. */
} TIM_TimeBaseInitTypeDef;
- TIM_Prescaler:时钟信号分频值,也就是设置上面PSC Prescaler对应的值,这个值可以设置为0x0000-0xFFFF,也就是0-65535,对应寄存器为TIMx prescaler (TIMx_PSC):
经过PSC预分频器,进入计数器的时钟信号频率为:
f C K _ P S C / ( P S C + 1 ) f_{CK\_PSC}/(PSC+1) fCK