您的位置 首页 开关

STM32定时器PWM输出

脉冲宽度调制PWM(PulseWidthModulation),调节占空比以控制脉冲宽度。STM32的定时器除了TIM6和TIM7,其它定时器都可以用来产…

  脉冲宽度调制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);
}

声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/dianyuan/kaiguan/272313.html

为您推荐

联系我们

联系我们

在线咨询: QQ交谈

邮箱: kf@86ic.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部