stm32 (timer and PWM knowledge points)

1. Introduction to timers

Software timing disadvantages: imprecise, occupying CPU resources

void Delay500ms() //@11.0592MHz
{
unsigned char i, j, k;
_nop_();
i = 4;
j = 129;
k = 119;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}

How the timer works:

Use an accurate time base to implement timing functions through hardware. The core of the timer is the counter.

 Timer classification:

  • Basic timer (TIM6~TIM7)
  • General timer (TIM2~TIM5)
  • Advanced timers (TIM1 and TIM8)

STM32F103C8T6 timer resources: 

 

 Timer clock source

 

 PSC is the prescaler and RCC is the auto-reload register

2. Introduction to PWM

STM32F103C8T6 PWM resources:

Advanced timer (TIM1): 7 channels

General timer (TIM2~TIM4): 4 channels each

PWM output mode:

  • PWM mode 1: When counting up, once CNT < CCRx, the output is a valid level, otherwise it is an invalid level; When counting down, once CNT > CCRx, the output is an invalid level, otherwise it is a valid level .
  • PWM mode 2: When counting up, once CNT < CCRx, the output is an invalid level, otherwise it is a valid level; When counting down, once CNT > CCRx, the output is a valid level, otherwise it is an invalid level .

 PWM experiment

Requirement: Use PWM to light up LED1 to achieve the breathing light effect.

Why do LED lights get brighter and darker?

This is determined by different duty cycles.

How to calculate period/frequency?

If the frequency is 2kHz, then: PSC=71, ARR=499

72*5000/72000000=0.0005       =          1/20000=0.0005

 Set timer

Business code 

// 定义变量
uint16_t pwmVal=0; //调整PWM占空比
uint8_t dir=1; //设置改变方向。1:占空比越来越大;0:占空比越来越小
// 使能 Timer4 第3通道 PWM 输出
HAL_TIM_PWM_Start(&htim4,TIM_CHANNEL_3);
// while循环实现呼吸灯效果
while (1)
{
HAL_Delay(1);
if (dir)
pwmVal++;
else
pwmVal--;
if (pwmVal > 500)
dir = 0;
if (pwmVal == 0)
dir =1;
//修改比较值,修改占空比
__HAL_TIM_SetCompare(&htim4, TIM_CHANNEL_3, pwmVal);
}

 

 

Guess you like

Origin blog.csdn.net/m0_70987863/article/details/131642134