stm32F103 TIM3 两路PWM输出,第一个波形的相位差是错的

2019-08-14 19:10发布

stm32F103 TIM3 两路PWM输出,第一个波形的相位差是错的

pwm采用了TIM_OCMode_Toggle模式,是TIM3 的CH1和CH2,在1ms内输出指定数量的波形。

基本能正常工作,但是现在有一个问题,偶然发现的!!!
第一个pwm脉冲的相位是错的,也就是说本来应该是ch1超前的,输出第一个pwm脉冲是错的,往后的脉冲都是对的。

明天上图。

程序是参考了群里大牛的,有原子哥,还有几个大牛的代码;
谁遇到过这种问题???

参考代码如下:
/******************************************************************
TIM3 Êä³&#246WMÅäÖÃ-2·
ÔÚ1msʱ¼äÄÚ£¬¹Ì¶¨Êä³önum¸ö²¨ÐÎ,Õ¼¿Õ±È¹Ì¶¨Îª50%duty
dir - 0:CH1³¬Ç°£¬1-CH2³¬Ç°
num - Êä³öÂö³å¸öÊý
ena - 0-¹Ø±ÕÊä³ö£¬1-ÔÊÐíÊä³ö
******************************************************************/
void TIM3_ABZ_Configuration(u8 dir,u8 num,u8 ena)
{
    u32 period = (4000/(num*2)-1);
   
    /* Time Base configuration */
  TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
  TIM_OCInitTypeDef TIM_OCInitStructure;
  TIM_BDTRInitTypeDef TIM_BDTRInitStructure;

  TIM_TimeBaseStructure.TIM_Prescaler = 17;        //4M
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up ;
    TIM_TimeBaseStructure.TIM_Period = period;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Disable;
    if(dir == 0)
    {   
        TIM_OCInitStructure.TIM_Pulse = period/2;
    }
    else
    {
        TIM_OCInitStructure.TIM_Pulse = 0;
    };
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
  TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
  TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset;
  TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;
   
  TIM_OC1Init(TIM3, &TIM_OCInitStructure);
  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
   
  //TIM1_OC2 config
  if(dir == 0)
    {   
        TIM_OCInitStructure.TIM_Pulse = 0;
    }
    else
    {
        TIM_OCInitStructure.TIM_Pulse = period/2;
    };
  TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset;
  TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;   
  TIM_OC2Init(TIM3, &TIM_OCInitStructure);
  TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);

  //ÉèÖÃËÀÇø
  TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Enable;
  TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Disable;
  TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_1;
  TIM_BDTRInitStructure.TIM_DeadTime = 2;  //0-0xff
  TIM_BDTRInitStructure.TIM_Break = TIM_Break_Enable;
  TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_Low;
  TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Enable;
  TIM_BDTRConfig(TIM3, &TIM_BDTRInitStructure);

  if(ena == 0)
    {
        TIM3_ABZ_Close();
    }
    else
    {
        /* TIM1 counter enable */
        TIM_Cmd(TIM3, ENABLE);

        /* TIM1 Main Output Enable */
        TIM_CtrlPWMOutputs(TIM3, ENABLE);
    };   
}

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