STM32F1高级定时器做普通PWM输出配置(例TIM1)

Posted pacexdong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了STM32F1高级定时器做普通PWM输出配置(例TIM1)相关的知识,希望对你有一定的参考价值。

TIM1的四个通道做PWM输出配置

void pwm_time1()

{  

GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;

RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);

GPIO_InitStructure.GPIO_Pin=GPIO_Pin_8|GPIO_Pin_9|GPIO_Pin_10|GPIO_Pin_11;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; 
GPIO_Init(GPIOA,&GPIO_InitStructure);

TIM_TimeBaseInitStructure.TIM_Period = 1999;

TIM_TimeBaseInitStructure.TIM_Prescaler = 7199;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1 ;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_RepetitionCounter =0;
TIM_TimeBaseInit(TIM1, & TIM_TimeBaseInitStructure);

TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse=0;
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState=TIM_OCIdleState_Set;
TIM_OC1Init(TIM1,&TIM_OCInitStructure);

TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse=0;
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState=TIM_OCIdleState_Set;
TIM_OC2Init(TIM1,&TIM_OCInitStructure);

TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse=0;
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState=TIM_OCIdleState_Set;
TIM_OC3Init(TIM1,&TIM_OCInitStructure);

TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse=0;
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState=TIM_OCIdleState_Set;
TIM_OC4Init(TIM1,&TIM_OCInitStructure);

 

TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OC2PreloadConfig(TIM1, TIM_OCPreload_Enable);

TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OC4PreloadConfig(TIM1, TIM_OCPreload_Enable);

TIM_Cmd(TIM1,ENABLE);

TIM_CtrlPWMOutputs(TIM1, ENABLE);

}

 

 

配置完成之后使用以下代码即可(可用示波器或逻辑分析仪检测方波)

TIM_SetCompare4(TIM1, 100);
TIM_SetCompare3(TIM1, 200);
TIM_SetCompare2(TIM1, 300);
TIM_SetCompare1(TIM1, 400);

以上是关于STM32F1高级定时器做普通PWM输出配置(例TIM1)的主要内容,如果未能解决你的问题,请参考以下文章

STM32f103ZET6 TIM8输出PWM波形

基于霸道秉火的STM32F103ZET6嵌入式开发之------基于定时TIM3的PWM实验

怎样使stm32f4内部产生正弦波驱动wm8978发出声音

STM32F103ZET6 用定时器级联方式输出特定数目的PWM(转载)

STM32定时器输出PWM频率和步进电机控制速度计算

STM32定时器输出PWM频率和步进电机控制速度计算