// PWM 初始化 包含通用定时器的初始化
// 使用TIM3 定时器 通道2 映射到PB5输出PWM
void PWM_Config(uint16_t arr,uint16_t psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
// 开启TIM3 时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
// 开启PB5时钟和时钟复用功能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO, ENABLE);
// 重映射 TIM3_CH2->PB5
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3, ENABLE);
// 初始化GPIO
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推完输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 初始化定时器
TIM_TimeBaseStructure.TIM_Period = arr; //自动重装载周期值
TIM_TimeBaseStructure.TIM_Prescaler =psc; //预分频值
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
// 初始化TIM3 CH2 PWM模式
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //PWM模式2
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性高
TIM_OC2Init(TIM3, &TIM_OCInitStructure); //初始化外设TIM3 OC2
TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_Cmd(TIM3, DISABLE); //使能TIM3
}
|