赞
踩
最近在做关于舵机的项目,需要输出4路pwm波控制舵机,看到好多代码只有单独的,索性将自己搜集整理的TIM3定时器4路输出PWM代码分享以下(库函数)
C8T6的TIM3的4个通道分别对应IO口为:
CH1——A6
CH2——A7
CH3——B0
CH4——B1
下面是初始化函数
- /* PWM初始化函数 */
- void PWM_Init_Servo(u16 Psc,u16 Arr)
- {
- /********************
- PB0和PB1输出PWM初始化
- **********************/
- GPIO_InitTypeDef GPIO_InitStruct;
- TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
- TIM_OCInitTypeDef TIM_OCInitStruct; //结构体定义
-
-
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO,ENABLE); //开启时钟
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
-
- GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP; //初始化GPIOB
- GPIO_InitStruct.GPIO_Pin=GPIO_Pin_0|GPIO_Pin_1;
- GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
- GPIO_Init(GPIOB,&GPIO_InitStruct);
-
- GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP; //初始化GPIOA
- GPIO_InitStruct.GPIO_Pin=GPIO_Pin_6|GPIO_Pin_7;
- GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
- GPIO_Init(GPIOA,&GPIO_InitStruct);
-
- TIM_TimeBaseStructInit(&TIM_TimeBaseInitStruct); //初始化定时器
- TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1;
- TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;
- TIM_TimeBaseInitStruct.TIM_Period=Arr;
- TIM_TimeBaseInitStruct.TIM_Prescaler=Psc;
- TIM_TimeBaseInitStruct.TIM_ClockDivision=0;
- TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStruct);
-
- TIM_OCInitStruct.TIM_OCMode=TIM_OCMode_PWM1; //初始化输出比较
- TIM_OCInitStruct.TIM_OCPolarity=TIM_OCPolarity_High;
- TIM_OCInitStruct.TIM_OutputState=TIM_OutputState_Enable;
- TIM_OCInitStruct.TIM_Pulse=0;
-
- TIM_OC1Init(TIM3,&TIM_OCInitStruct ); //初始化4通道1:A6 2:A7 3:B0 4:B1
- TIM_OC2Init(TIM3,&TIM_OCInitStruct );
- TIM_OC3Init(TIM3,&TIM_OCInitStruct );
- TIM_OC4Init(TIM3, &TIM_OCInitStruct);
-
- TIM_OC1PreloadConfig(TIM3,TIM_OCPreload_Enable);
- TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable);
- TIM_OC3PreloadConfig(TIM3,TIM_OCPreload_Enable); //OC1-OC4装载寄存器使能
- TIM_OC4PreloadConfig(TIM3,TIM_OCPreload_Enable);
-
- TIM_ARRPreloadConfig(TIM3,ENABLE); //TIM3在APR上预装载寄存器使能
-
- TIM_Cmd(TIM3,ENABLE); //开定时器
-
-
- }
主函数调用示例:
PWM_Init_Servo(143,9999);
装载值函数:
- u16 PWM=750;
- TIM_SetCompare1(TIM3, PWM);
- TIM_SetCompare2(TIM3, PWM);
- TIM_SetCompare3(TIM3, PWM);
- TIM_SetCompare4(TIM3, PWM);
参考了好多大佬的文章,如有错误请大家指出!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。