Bowman
Bowman

Reputation: 109

Changing Duty Cycle and Frequency of PWM Together

I have 4 buttons. I want to change duty cycle and frequency of PWM which is created by TIM1.

Two buttons for frequency to make it higher or lower. Other two buttons for duty cycle to make it higher or lower.

I managed to change frequency of PWM with this function:

uint8_t loop = 0;

void FreqAdjust(uint8_t loop)
{
    switch(loop)
    {
          case 0:
            __HAL_TIM_SET_AUTORELOAD(&htim1,60); // 27khz
            __HAL_TIM_SET_PRESCALER(&htim1,100);
            __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_3,30);
            break;
          case 1:
            __HAL_TIM_SET_AUTORELOAD(&htim1,60); // 28khz
            __HAL_TIM_SET_PRESCALER(&htim1,96);
            __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_3,30);
            break;
          case 2:
            __HAL_TIM_SET_AUTORELOAD(&htim1,60); // 29khz
            __HAL_TIM_SET_PRESCALER(&htim1,93);
            __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_3,30);
            break;
          case 3:
            __HAL_TIM_SET_AUTORELOAD(&htim1,60); // 30khz
            __HAL_TIM_SET_PRESCALER(&htim1,90);
            __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_3,30);
            break;
          case 4:
            __HAL_TIM_SET_AUTORELOAD(&htim1,60); // 31khz
            __HAL_TIM_SET_PRESCALER(&htim1,90);
            __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_3,30);
                break;
    }
}

I also want to change duty cycle too. How can i do that ? Should i change the method ?

Upvotes: 0

Views: 1116

Answers (1)

Kiboxxx
Kiboxxx

Reputation: 23

The duty cycle depends on the autoreload register in relation to the output compare register. So to change the duty cycle, you would have to adjust both values accordingly.

        __HAL_TIM_SET_AUTORELOAD(&htim1,60); // 31khz
        __HAL_TIM_SET_PRESCALER(&htim1,90);
        __HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_3,30);

creates in your case a frequency of 31 kHz with a duty cycle of 50 %. If you change the compare value to 20, it´s 30 %. So just use variables for the "60" and the "30" and write an extra function where you can specify your duty cycle and your values are calculated accordingly.

Upvotes: 0

Related Questions