新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設計應用 > STM32定時器PWM輸出

STM32定時器PWM輸出

作者: 時間:2016-11-13 來源:網(wǎng)絡 收藏
  脈沖寬度調制PWM(Pulse Width Modulation),調節(jié)占空比以控制脈沖寬度。

  STM32定時器除了TIM6和TIM7,其它定時器都可以用來產生PWM信號,高級定時器TIM1和TIM8可同時產生7路PWM輸出,通用定時器可同時產生4路PWM輸出。

本文引用地址:http://m.butianyuan.cn/article/201611/316143.htm

  出設置的幾個步驟如下:

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;    // 設定計數(shù)器自動重裝值 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;   // 調節(jié)占空比

}

  因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;// 調節(jié)占空比TIM3_CH1
  TIM3->CCR2 = 300;// 調節(jié)占空比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);
}



關鍵詞: STM32定時器PWM輸

評論


技術專區(qū)

關閉