发 帖  
stm8s pwm输出代码
2018-7-4 02:06:33  155 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);
   }
}

void TestPWM_Beep(void)
{
   u8 i;
   for(i=0;i<7;i++)
   {
     SetTIM2_PWM_Frequency(Beep_Frequency);
     Delay(0xffff);
     Delay(0xffff);
     Delay(0xffff);
     Delay(0xffff);
     Delay(0xffff);
     Delay(0xffff);
     Delay(0xffff);

   }
}
static void Delay(u16 nCount)
{
   /* Decrement nCount value */
   while (nCount != 0)
   {
     nCount--;
   }
}


        10-PWM.rar

0
2018-7-4 02:06:33   评论

只有小组成员才能发言,加入小组>>

304个成员聚集在这个小组

加入小组

创建小组步骤

关闭

站长推荐 上一条 /7 下一条

快速回复 返回顶部 返回列表