posted in: Microcontroller | 0

1. Introduction to PWM

Pulse Width Modulation (PWM) is a method of pulse width modulation or adjustment of the output voltage intensity value. PWM is commonly used in motor control.

Some of the concepts of PWM include:

  • Duty cycle : high pulse percentage.
  • Period : is the pulse period (including the total time high + low).
  • Pulse width is the value of the high relative to the period. لعبة القمار
  • PTO is a square pulse with 50% high time, 50% low time.
  • Pulse amplitude: is the voltage value of the pulse when it is high.

Duty cycle calculation formula:

Duty cycle = pulse width x 100/period

2. PWM in STM32F103C8T6

This microcontroller has 4 Timers: TIM1, TIM2, TIM3, TIM4 to generate PWM pulses. Each channel has 4 small channels, Timer 1 alone has 4 more island channels. وليام هيل  For simple PWM modulation applications, it is common to use one of the other three Timers. الروليت اون لاين

3. Programming with the ST library

In this article, I will use TIM2 – channle 4 to generate PWM pulses with Duty cycle of 75%.

  • Clock level and timer configuration 2 channel 4
/*Cap clock*/
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
/*Cau hinh chân*/
GPIO_InitStructure.GPIO_Pin  = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* cau hinh timer base */
TIM_TimeBaseStructure.TIM_Prescaler = 7199;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = 9999;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
  • Configure PWM mode
 /* cau hinh channel4 o mode PWM */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 7500;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
  TIM_OC4Init(TIM2, &TIM_OCInitStructure);
  TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Enable);
  TIM_ARRPreloadConfig(TIM2, ENABLE);
  /* cho phep TIM2 hoat dong */
  • Duty cycle adjustment function

The function TIM_SetComparex(TIMy,z) is used to adjust the pulse width of the PWM channel configuring SetComparex to correspond to the x channel of TIMy with the value z. So, if to generate a 75% PWM pulse, we have the formula: Duty cycle = 7500/(9999 + 1)*100 = 75%

Note: In the article, the pulse is configured as 7500, so there is no need to use this adjustment function.

Sample code link

Leave a Reply

Your email address will not be published. Required fields are marked *