定时器PWM初始化示例,C8T6的板
因为开发板的LED灯引脚PA1同时也是TIM2_CH2引脚,这里使用了引脚复用功能,没有重映射
/**
* [url=home.php?mod=space&uid=139335]@name[/url] TIM_PWM_Init
* [url=home.php?mod=space&uid=247401]@brief[/url] 定时器PWM初始化
* @param arr:自动重装值
* psc:时钟预分频系数
* @retval None
*/
void TIM_PWM_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitTypeDefStructure;
//使能定时器2时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
//使能GPIOA时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
//PA1配置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //设置为复用推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//PA1初始化
GPIO_Init(GPIOA,&GPIO_InitStructure);
//把PA1用作定时器的PWM输出引脚。初始化定时器
TIM_TimeBaseInitStructure.TIM_Period = arr; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值
TIM_TimeBaseInitStructure.TIM_Prescaler = psc;//设置用来作为TIMx时钟频率除数的预分频值
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割:TDTS = Tck_tim
//定时器2初始化
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
//通道2配置
TIM_OCInitTypeDefStructure.TIM_OCMode = TIM_OCMode_PWM2; //PWM模式2
TIM_OCInitTypeDefStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitTypeDefStructure.TIM_Pulse = 100;
TIM_OCInitTypeDefStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性:TIM输出比较极性高
//初始化输出比较参数
TIM_OC2Init(TIM2,&TIM_OCInitTypeDefStructure);
//使能预装载寄存器
TIM_OC2PreloadConfig(TIM2,TIM_OCPreload_Enable);
//使能定时器
TIM_Cmd(TIM2,ENABLE);
}
|