微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > STM32定时器PWM输出

STM32定时器PWM输出

时间:11-13 来源:互联网 点击:
  脉冲宽度调制PWM(Pulse Width Modulation),调节占空比以控制脉冲宽度。

STM32定时器除了TIM6和TIM7,其它定时器都可以用来产生PWM信号,高级定时器TIM1和TIM8可同时产生7路PWM输出,通用定时器可同时产生4路PWM输出。

STM32定时器PWM输出设置的几个步骤如下:

1)开启STM32时钟,配置输出I/O为复用输出

2)设置ARR(周期)和PSC(预分频)

3)设置PWM模式(边沿对齐或中央对齐)

4)使能定时器的通道输出,使能定时器

5)修改CCR2来控制占空比

例程:72MHz主频,PB7(TIM4_CH2)输出PWM

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;// for PWM
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);

void TIM4_Configuration(void)// for PWM
{
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);

  TIM4->ARR = 900;    // 设定计数器自动重装值 72MHz/900 = 8kHz
  TIM4->PSC = 0;     // 预分频器不分频
  TIM4->CCMR1 |= 7<12; // PWM2
  TIM4->CCMR1 |= 1<11; // CH2预装载使能
  TIM4->CCER |= 1<4;  // OC2输出使能
  TIM4->CR1 |= 0x8000;  // ARPE使能
  TIM4->CR1 |= 0x01;   // 使能定时器
  TIM4->CCR2 = 550;   // 调节占空比

}

因IAR固件库每个版本不同,该例程直接对寄存器进行控制,以方便理解。

补充一个基于固件库的例程(以TIM3为例,省略IO设置部分):

void TIM3_Configuration(void)
{
  // 输出两路PWM
  /*----------------------------------------------------------
  RCC_APB2PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

  TIM3->ARR = 900;// 最大900
  TIM3->PSC = 0;
  TIM3->CCMR1 |= 7<12;// PWM2 中央对齐
  TIM3->CCMR1 |= 1<11;// CH2预装载使能
  TIM3->CCER |= 1<4;// OC2输出使能

  TIM3->CCMR1 |= 7<4;// PWM2 中央对齐
  TIM3->CCMR1 |= 1<3;// CH1预装载使能
  TIM3->CCER |= 1;// OC1输出使能

  TIM3->CR1 |= 0x8000;// ARPE使能
  TIM3->CR1 |= 0x01;// 使能定时器
  TIM3->CCR1 = 100;// 调节占空比TIM3_CH1
  TIM3->CCR2 = 300;// 调节占空比TIM3_CH2
  -----------------------------------------------------------*/

  TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
  TIM_OCInitTypeDef TIM_OCInitStructure;

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

  TIM_TimeBaseStructure.TIM_Period = 999;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  /* PWM1 Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 500;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
  TIM_OC1Init(TIM3, &TIM_OCInitStructure);
  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);

  /* PWM1 Mode configuration: Channel2 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 300;
  TIM_OC2Init(TIM3, &TIM_OCInitStructure);
  TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);

  TIM_ARRPreloadConfig(TIM3, ENABLE);
  TIM_Cmd(TIM3, ENABLE);
}

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top