-
在使用定时器(TIM)进行脉冲宽度调制(PWM)时,除了使能定时器本身(通过TIM_Cmd(TIM2, ENABLE))外,还需要使用TIM_CtrlPWMOutputs(TIM2,ENABLE)函数来启用PWM输出。
-
TIM_Cmd(TIM2, ENABLE)函数用于使能定时器 TIM2,这将启动定时器的计数以及相关的功能。
-
TIM_CtrlPWMOutputs(TIM2, ENABLE)函数用于启用定时器 TIM2 的 PWM 输出功能。这个函数在某些 MCU 中是必需的,因为在某些定时器中,使能 PWM 输出功能是一个独立的步骤。
-
在没有调用TIM_CtrlPWMOutputs(TIM2, ENABLE)函数时,定时器会正常计数,但不会输出 PWM 波形。因此,只有在调用该函数之后,才能看到 PWM 波形正常输出。
TIM_Cmd(TIM2, ENABLE);
TIM_CtrlPWMOutputs(TIM2,ENABLE);
PWM初始化代码如下:
#include "stm32f4xx.h" // Device header
/*
电机驱动
pa15---tim2_ch1
20khz 50%占空比 1%分辨率 ---ARR100 PSC90 CCR50
1/20ms = 50hz ---20k=20ms
*/
void PWM_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);//
GPIO_InitTypeDef GPIO_InitStructure;
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;//
// GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;//
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA,GPIO_PinSource15 ,GPIO_AF_TIM2);
TIM_InternalClockConfig(TIM2);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_Period = 100 - 1; //ARR 100
TIM_TimeBaseInitStructure.TIM_Prescaler = 90 - 1; //PSC 90
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure);
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCStructInit(&TIM_OCInitStructure);//给结构体赋初始值
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0; //CCR
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
TIM_Cmd(TIM2, ENABLE);
TIM_CtrlPWMOutputs(TIM2,ENABLE);
}
void PWM_SetCompare1(uint16_t Compare)
{
TIM_SetCompare1(TIM2, Compare);
}