STM 32的PWM的频率和占空比设定

在TEC控温项目中用到PWM的占空比来控制温度,这就需要占空比是连续可以变化的。

最开始也是到处找资料,找现成的例程,发现大家各说风云,最后还是没有建设性的结果。所以又请教了官方的固件库“STM32最新固件库v3.5”(存到百度网盘->开发应用->stm32目录下了)呵呵,有现成的demo。开始好像是懂了也没有过多的去研究,也没有备份,就没去管他了。后来具体用的时候发现没有想象的那么简单,又倒腾了好久才搞清楚,问了不走弯路。这次决定用博客来记录一下现在的成果。配置文件如下:

void TIME_ini(uint16_t Channel4Pulseset)
{
TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
  TIM_OCInitTypeDef  TIM_OCInitStructure;
  uint16_t TimerPeriod ;
  uint16_t Channel4Pulse = 0;

  RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1 | RCC_APB2Periph_AFIO, ENABLE);

  /* Time Base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 0;//不分频,PWM的频率为72M/((TIM_Prescaler +1)*TIM_Period )
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = 0xfff;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;

  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  /* Channel  4 Configuration in PWM mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;

  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
  TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
  TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;

  TIM_OCInitStructure.TIM_Pulse = Channel4Pulseset;               //占空比=TIM_Pulse /TIM_Period                        
  TIM_OC4Init(TIM1, &TIM_OCInitStructure);

  TIM_Cmd(TIM1, ENABLE);
  TIM_CtrlPWMOutputs(TIM1, ENABLE);
}

定时器1在不分频的情况下始终频率是72M,所以设置PWM的频率=72M/((TIM_Prescaler +1)*TIM_Period );

占空比=TIM_Pulse /TIM_Period     

你可能感兴趣的:(单片机世界)