cancel
Showing results for 
Search instead for 
Did you mean: 

How to change the frequency of the PWM using potentiometer

RSy.1
Associate III

Hello guys good day to you. May I ask you if you can share your experience on changing the frequency of a PWM using a pot. I am using a small board with the STM32F103C8 MCU.

I've set TIM2 _CH1 of PA0 as output. I connected a potentiometer to PA2 (ADC1_IN2 ) to vary the frequency. I am using CubeMX to configure the MCU. Here are the other details:

MCU clock set to 48MHz

ADC clock set to 12MHz

TIM2 prescale to 47

TIM2 ARR set to 0 (I am thinking of modifying the htim period line to vary the frequency)

I used the HAL_ADC_ConvCpltCallback to enable the ADC.

void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef * hadc)

{

htim2.Init.Period = ADValue/4; //I was thinking I could vary the frequency this way

TIM2 -> CCR1 = (ADValue/8); //Set duty cycle to 50%

}

However I do not see the TIM2_CH1 having output at all. Can you tell me what is wrong and how to correct this? Thank you for your time.

4 REPLIES 4
TDK
Guru

> TIM2 ARR set to 0

Your timer will not run with ARR=0. See the reference manual.

> htim2.Init.Period = ADValue/4;

This doesn't do anything but change a value in memory. It doesn't actually modify the timer register (which is done in HAL_TIM_Base_Init). You probably want

TIM2->ARR = ADValue / 4;

If you feel a post has answered your question, please click "Accept as Solution".
RSy.1
Associate III

Thank you Sir I will try this code.

RSy.1
Associate III

I tried this code:

void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)

{

TIM2 -> ARR = ((ADValue1[0])/4); //vary the frequency

TIM2 -> CCR1 = ((ADValue1[0])/4)/2; //Set duty cycle to 50%

}

It is working but I noticed the LED output is jittery. I am expecting for a smooth transition but the waveform/output is not stable.

You want to set both ARR and CCRx being preloaded. Read the RM. Maybe Cube does this fit you, I don't know, I don't use Cube

JW