资深版主
- 积分
- 10541
- 金钱
- 10541
- 注册时间
- 2017-2-18
- 在线时间
- 1908 小时
|
有人问到F407TIM1进行PWM输出的问题
可以用附件中的程序进行测试,测试程序基于探索者F407板子
整个工程最重要的是TIM1_PWM_Init(),具体如下:
[mw_shl_code=c,true]//TIM1 PWM部分初始化
//arr:自动重装值
//psc:时钟预分频数
void TIM1_PWM_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE); //TIM1时钟使能
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE); //使能PORTA时钟
GPIO_PinAFConfig(GPIOA,GPIO_PinSource8,GPIO_AF_TIM1); //GPIOA8复用为定时器1
GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_TIM1); //GPIOA9复用为定时器1
GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_TIM1); //GPIOA10复用为定时器1
GPIO_PinAFConfig(GPIOA,GPIO_PinSource11,GPIO_AF_TIM1); //GPIOA11复用为定时器1
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8|GPIO_Pin_9|GPIO_Pin_10|GPIO_Pin_11; //GPIOA8,GPIOA9,GPIOA10,GPIOA11
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; //复用功能
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; //不上下拉
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度100MHz
GPIO_Init(GPIOA,&GPIO_InitStructure); //初始化PA8,PA9,PA10,PA11
TIM_TimeBaseStructure.TIM_Prescaler = psc; //定时器分频
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数模式
TIM_TimeBaseStructure.TIM_Period = arr; //自动重装载值
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM1,&TIM_TimeBaseStructure); //初始化定时器1
//初始化TIM1 Channel1,2,3,4 PWM模式
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //选择定时器模式:TIM脉冲宽度调制模式2
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitStructure.TIM_Pulse = arr;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性高
TIM_OC1Init(TIM1, &TIM_OCInitStructure); //根据T指定的参数初始化外设OC1
TIM_OC2Init(TIM1, &TIM_OCInitStructure); //根据T指定的参数初始化外设OC2
TIM_OC3Init(TIM1, &TIM_OCInitStructure); //根据T指定的参数初始化外设OC3
TIM_OC4Init(TIM1, &TIM_OCInitStructure); //根据T指定的参数初始化外设OC4
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable); //使能TIM1在CCR1上的预装载寄存器
TIM_OC2PreloadConfig(TIM1, TIM_OCPreload_Enable); //使能TIM1在CCR2上的预装载寄存器
TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable); //使能TIM1在CCR3上的预装载寄存器
TIM_OC4PreloadConfig(TIM1, TIM_OCPreload_Enable); //使能TIM1在CCR4上的预装载寄存器
TIM_ARRPreloadConfig(TIM1,ENABLE); //ARPE使能
TIM_CtrlPWMOutputs(TIM1,ENABLE); //使能TIM1的PWM输出
TIM_Cmd(TIM1,ENABLE); //使能TIM1
}
[/mw_shl_code]
main函数中调用TIM_SetComparex()来设置占空比
[mw_shl_code=c,true]int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//设置系统中断优先级分组2
delay_init(168); //初始化延时函数
TIM1_PWM_Init(500-1,168-1); //84M/84=1Mhz的计数频率,重装载值500,所以PWM频率为 1M/500=2Khz.
TIM_SetCompare1(TIM1,250); //修改占空比
TIM_SetCompare2(TIM1,250); //修改占空比
TIM_SetCompare3(TIM1,250); //修改占空比
TIM_SetCompare4(TIM1,250); //修改占空比
}[/mw_shl_code]
|
|