Board logo

标题: stm8s pwm输出代码 [打印本页]

作者: yuchengze    时间: 2016-12-23 20:39     标题: stm8s pwm输出代码

#include "pwm.h"

static void Delay(u16 nCount);
u16 Beep_Frequency[7]={3816,3400,3029,2864,2550,2272,2023};

void PWM_Init(void)
{

  #if PWM_Channel==PWM_Channel1
    /*TIM2 Frequency = TIM2 counter clock/(ARR + 1) */
    TIM2_TimeBaseInit(TIM2_PRESCALER_16, 499);
    /*TIM2 Frequency=16M/16/(499+1)=2K*/
    /* PWM1 Mode configuration: Channel1
    TIM2 Channel1 duty cycle = [TIM2_CCR1/(TIM2_ARR + 1)] * 100 = 50%*/
    TIM2_OC1Init(TIM2_OCMODE_PWM1, TIM2_OUTPUTSTATE_ENABLE,250, TIM2_OCPOLARITY_HIGH);
    TIM2_OC1PreloadConfig(ENABLE);

  #elif PWM_Channel==PWM_Channel2
    TIM2_TimeBaseInit(TIM2_PRESCALER_16, 999);
    TIM2_OC2Init(TIM2_OCMODE_PWM2, TIM2_OUTPUTSTATE_ENABLE,500, TIM2_OCPOLARITY_HIGH);
    TIM2_OC2PreloadConfig(ENABLE);

  #elif PWM_Channel==PWM_Channel3
    TIM2_TimeBaseInit(TIM2_PRESCALER_16, 499);
    TIM2_OC3Init(TIM2_OCMODE_PWM1, TIM2_OUTPUTSTATE_ENABLE,250, TIM2_OCPOLARITY_HIGH);
    TIM2_OC3PreloadConfig(ENABLE);
  #endif

  TIM2_Cmd(ENABLE);

}

void SetTIM2_PWM_Frequency(uint16_t TIM2_Period)
{
      /* Set the Autoreload value */

    TIM2->ARRH = (uint8_t)(TIM2_Period >> 8);
    TIM2->ARRL = (uint8_t)(TIM2_Period);
}

void SetTIM2_PWM_DutyCycle( uint16_t TIM2_Pulse)
{


  #if PWM_Channel==PWM_Channel1
    /* Set the Pulse value */
    TIM2->CCR1H = (uint8_t)(TIM2_Pulse >> 8);
    TIM2->CCR1L = (uint8_t)(TIM2_Pulse);

  #elif PWM_Channel==PWM_Channel2
    TIM2->CCR2H = (uint8_t)(TIM2_Pulse >> 8);
    TIM2->CCR2L = (uint8_t)(TIM2_Pulse);

  #elif PWM_Channel==PWM_Channel3
    TIM2->CCR3H = (uint8_t)(TIM2_Pulse >> 8);
    TIM2->CCR3L = (uint8_t)(TIM2_Pulse);

  #endif
}

void TestPWM_LED(void)
{
  u16 Duty_Val;
  for(Duty_Val=0;Duty_Val<499;Duty_Val++)
  {
    SetTIM2_PWM_DutyCycle(Duty_Val);
    Delay(0xfff);
  }
}





欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) Powered by Discuz! 7.0.0