STM32定時(shí)器PWM輸出
STM32的定時(shí)器除了TIM6和TIM7,其它定時(shí)器都可以用來產(chǎn)生PWM信號(hào),高級(jí)定時(shí)器TIM1和TIM8可同時(shí)產(chǎn)生7路PWM輸出,通用定時(shí)器可同時(shí)產(chǎn)生4路PWM輸出。
本文引用地址:http://m.butianyuan.cn/article/201611/316143.htmSTM32定時(shí)器PWM輸出設(shè)置的幾個(gè)步驟如下:
1)開啟STM32時(shí)鐘,配置輸出I/O為復(fù)用輸出
2)設(shè)置ARR(周期)和PSC(預(yù)分頻)
3)設(shè)置PWM模式(邊沿對(duì)齊或中央對(duì)齊)
4)使能定時(shí)器的通道輸出,使能定時(shí)器
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è)定計(jì)數(shù)器自動(dòng)重裝值 72MHz/900 = 8kHz
TIM4->PSC = 0; // 預(yù)分頻器不分頻
TIM4->CCMR1 |= 7<<12; // PWM2
TIM4->CCMR1 |= 1<<11; // CH2預(yù)裝載使能
TIM4->CCER |= 1<<4; // OC2輸出使能
TIM4->CR1 |= 0x8000; // ARPE使能
TIM4->CR1 |= 0x01; // 使能定時(shí)器
TIM4->CCR2 = 550; // 調(diào)節(jié)占空比
}
因IAR固件庫每個(gè)版本不同,該例程直接對(duì)寄存器進(jìn)行控制,以方便理解。
補(bǔ)充一個(gè)基于固件庫的例程(以TIM3為例,省略IO設(shè)置部分):
void TIM3_Configuration(void)
{
// 輸出兩路PWM
/*----------------------------------------------------------
RCC_APB2PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM3->ARR = 900;// 最大900
TIM3->PSC = 0;
TIM3->CCMR1 |= 7<<12;// PWM2 中央對(duì)齊
TIM3->CCMR1 |= 1<<11;// CH2預(yù)裝載使能
TIM3->CCER |= 1<<4;// OC2輸出使能
TIM3->CCMR1 |= 7<<4;// PWM2 中央對(duì)齊
TIM3->CCMR1 |= 1<<3;// CH1預(yù)裝載使能
TIM3->CCER |= 1;// OC1輸出使能
TIM3->CR1 |= 0x8000;// ARPE使能
TIM3->CR1 |= 0x01;// 使能定時(shí)器
TIM3->CCR1 = 100;// 調(diào)節(jié)占空比TIM3_CH1
TIM3->CCR2 = 300;// 調(diào)節(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);
}
評(píng)論