代码如下:
void T2CH2_PWM_Init(u32 freq, u8 dc) //PD3
{
GPIO_InitTypeDef GPIO_InitStructure={0};
TIM_OCInitTypeDef TIM_OCInitStructure={0};
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure={0};
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOD, ENABLE );
RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM2, ENABLE );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init( GPIOD, &GPIO_InitStructure );
TIM_TimeBaseInitStructure.TIM_Period = SystemCoreClock / 2400 / freq - 1;
TIM_TimeBaseInitStructure.TIM_Prescaler = 2400;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit( TIM2, &TIM_TimeBaseInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = TIM_TimeBaseInitStructure.TIM_Period * dc / 100;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init( TIM2, &TIM_OCInitStructure );
TIM_CtrlPWMOutputs(TIM2, ENABLE );
TIM_OC1PreloadConfig( TIM2, TIM_OCPreload_Disable );
TIM_ARRPreloadConfig( TIM2, ENABLE );
TIM_Cmd( TIM2, ENABLE );
}