当前位置:   article > 正文

stm32f103c8t6TIM3定时器4路输出PWM_stm32f103c8t6 tim3 pwm

stm32f103c8t6 tim3 pwm

最近在做关于舵机的项目,需要输出4路pwm波控制舵机,看到好多代码只有单独的,索性将自己搜集整理的TIM3定时器4路输出PWM代码分享以下(库函数)

C8T6的TIM3的4个通道分别对应IO口为:

CH1——A6

CH2——A7

CH3——B0

CH4——B1

下面是初始化函数

  1. /* PWM初始化函数 */
  2. void PWM_Init_Servo(u16 Psc,u16 Arr)
  3. {
  4. /********************
  5. PB0和PB1输出PWM初始化
  6. **********************/
  7. GPIO_InitTypeDef GPIO_InitStruct;
  8. TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
  9. TIM_OCInitTypeDef TIM_OCInitStruct; //结构体定义
  10. RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO,ENABLE); //开启时钟
  11. RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
  12. GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP; //初始化GPIOB
  13. GPIO_InitStruct.GPIO_Pin=GPIO_Pin_0|GPIO_Pin_1;
  14. GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
  15. GPIO_Init(GPIOB,&GPIO_InitStruct);
  16. GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP; //初始化GPIOA
  17. GPIO_InitStruct.GPIO_Pin=GPIO_Pin_6|GPIO_Pin_7;
  18. GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
  19. GPIO_Init(GPIOA,&GPIO_InitStruct);
  20. TIM_TimeBaseStructInit(&TIM_TimeBaseInitStruct); //初始化定时器
  21. TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1;
  22. TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;
  23. TIM_TimeBaseInitStruct.TIM_Period=Arr;
  24. TIM_TimeBaseInitStruct.TIM_Prescaler=Psc;
  25. TIM_TimeBaseInitStruct.TIM_ClockDivision=0;
  26. TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStruct);
  27. TIM_OCInitStruct.TIM_OCMode=TIM_OCMode_PWM1; //初始化输出比较
  28. TIM_OCInitStruct.TIM_OCPolarity=TIM_OCPolarity_High;
  29. TIM_OCInitStruct.TIM_OutputState=TIM_OutputState_Enable;
  30. TIM_OCInitStruct.TIM_Pulse=0;
  31. TIM_OC1Init(TIM3,&TIM_OCInitStruct ); //初始化4通道1:A6 2:A7 3:B0 4:B1
  32. TIM_OC2Init(TIM3,&TIM_OCInitStruct );
  33. TIM_OC3Init(TIM3,&TIM_OCInitStruct );
  34. TIM_OC4Init(TIM3, &TIM_OCInitStruct);
  35. TIM_OC1PreloadConfig(TIM3,TIM_OCPreload_Enable);
  36. TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable);
  37. TIM_OC3PreloadConfig(TIM3,TIM_OCPreload_Enable); //OC1-OC4装载寄存器使能
  38. TIM_OC4PreloadConfig(TIM3,TIM_OCPreload_Enable);
  39. TIM_ARRPreloadConfig(TIM3,ENABLE); //TIM3在APR上预装载寄存器使能
  40. TIM_Cmd(TIM3,ENABLE); //开定时器
  41. }

主函数调用示例:

PWM_Init_Servo(143,9999); 

装载值函数:

  1. u16 PWM=750;
  2. TIM_SetCompare1(TIM3, PWM);
  3. TIM_SetCompare2(TIM3, PWM);
  4. TIM_SetCompare3(TIM3, PWM);
  5. TIM_SetCompare4(TIM3, PWM);

参考了好多大佬的文章,如有错误请大家指出!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/302086
推荐阅读
相关标签
  

闽ICP备14008679号