c8t6用TIM2的CH3,CH4输出PWM时,初始化TIM2出错,初始化TIM3则正常输出PWM

2019-07-20 23:19发布

本帖最后由 中华有为 于 2019-7-2 10:24 编辑
  1. <p>#include "l298n_control.h"

  2. //L298N初始化 PA4--IN1, PA5--IN2, PA6--IN3, PA7--IN4, PA2--ENA, PA3--ENB,
  3. void L298N_Init(u16 period, u16 prescaler)
  4. {
  5. GPIO_InitTypeDef GPIO_InitStructure;
  6. TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
  7. TIM_OCInitTypeDef TIM_OCInitStructure;
  8. </p><p>//使能时钟
  9. RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
  10. RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

  11. //PA4,PA5,PA6,PA7为推挽输出,L,R电机正反转控制引脚
  12. GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7; //L:IN1,IN2  R:IN3,IN4
  13. GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;         //推挽输出
  14. GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  15. GPIO_Init(GPIOA, &GPIO_InitStructure);
  16. GPIO_ResetBits(GPIOA, GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7);

  17. //PA0,PA1,PA2,PA3为复用推挽输出,PWM输出引脚
  18. GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3; //ENA,ENB
  19. GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;   //复用推挽输出
  20. GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  21. GPIO_Init(GPIOA, &GPIO_InitStructure);

  22. //初始化TIM2
  23. TIM_TimeBaseStructure.TIM_Period = period;      //设置自动装载周期值
  24. TIM_TimeBaseStructure.TIM_Prescaler = prescaler;    //设置预分频值
  25. TIM_TimeBaseStructure.TIM_ClockDivision = 0;     //设置时钟分割
  26. TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  //TIM向上计数
  27. TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);     //初始化

  28. //初始化TIM2 CH3-CH4 PWM模式
  29. TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;    //选择PWM2
  30. TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
  31. TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;  //极性高
  32. TIM_OC3Init(TIM2, &TIM_OCInitStructure);      //初始化CH3
  33. TIM_OC4Init(TIM2, &TIM_OCInitStructure);      //初始化CH4

  34. TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Enable); //使能CH3预装载寄存器
  35. TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Enable); //使能CH4预装载寄存器

  36. TIM_Cmd(TIM2, ENABLE); //使能TIM2
  37. }</p>
复制代码TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);改为TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);则能输出PWM,这个是哪里出错了呢,望大神斧正。


友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。