I'm trying to write a function that takes a desired frequency of PWM and sets the timer based on this value:
void initTimer(unsigned int freq ){
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseInitTypeDef timerInitStructure;
timerInitStructure.TIM_Prescaler = 1000;
timerInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
timerInitStructure.TIM_Period = 1000;
timerInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
timerInitStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM3, &timerInitStructure);
TIM_Cmd(TIM3, ENABLE);
TIM_OCInitTypeDef outputChannelInit;
outputChannelInit.TIM_OCMode = TIM_OCMode_PWM1;
outputChannelInit.TIM_Pulse = 500;
outputChannelInit.TIM_OutputState = TIM_OutputState_Enable;
outputChannelInit.TIM_OCPolarity = TIM_OCPolarity_High;
// the first channel
TIM_OC1Init(TIM3, &outputChannelInit);
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
GPIO_PinRemapConfig(GPIO_FullRemap_TIM3,ENABLE);
}
The code works fine and generates the expected PWM. My Problem is that I don't know how to calculate the value of the prescaler based on the given frequency. In the example above the values are fixed.
Any idea how may I do this? Thanks in advance!