cancel
Showing results for 
Search instead for 
Did you mean: 

PWM TIM1 frequency differs from calculation

Bogdan
Senior

Hello,

i have a simple task which turned to be more tricky than i expected.

The system uses a 8mhz HSE.

My clocks are :

HCLK/SYSCLK is 100MHZ

PCLK1 is 25MHZ

PCLK2 is 50 MHZ ( 100MHZ for TIM1)

I need to generate a 50% duty 100khz PWM signal via PE9 pin ( channel1 from TIMER1).

As i know the timer tick is tick = ( 1/(PCLK *2) ) * Prescale - 1 , the pwm frequency is 1/(tick * Preload)

Therefore for 100MHZ input, and for a PSC of 100 (101-1) and Period of 10 (11-1) i would expect a 100kHZ pwm signal, but the actual frequency is 81.2khz.

Why this huge diference? I also tried with lower frequencies, and the result is the same

I will show you the actual code

int main(void)
{
 
	SystemInit();
	 RCC_ClocksTypeDef clocks;
	  RCC_GetClocksFreq(&clocks);
     // uint32_t hs = HSE_VALUE;
 
 
 
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
 
 
	 GPIO_InitTypeDef GPIO_InitStruct;
	 TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	 TIM_OCInitTypeDef  TIM_OCInitStructure;
 
 
	 GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9  ;
	 GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
	 GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
	 GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
	 GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
	 GPIO_Init(GPIOE, &GPIO_InitStruct);
 
	 GPIO_PinAFConfig(GPIOE, GPIO_PinSource9, GPIO_AF_TIM1);
 
 
	 TIM_TimeBaseStructure.TIM_Prescaler = 101;
	 TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
	 TIM_TimeBaseStructure.TIM_Period = 11;
	 TIM_TimeBaseStructure.TIM_ClockDivision = 0;
	 TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
	 TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
 
 
 
 
	 TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;//
	 TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	 TIM_OCInitStructure.TIM_Pulse =5; // 50 %duty
	 TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
	 TIM_OC1Init(TIM1, &TIM_OCInitStructure);
 
        TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
	 TIM_ARRPreloadConfig(TIM1, ENABLE);
	 TIM_Cmd(TIM1, ENABLE);
 
	 TIM_CtrlPWMOutputs(TIM1, ENABLE);
 
	 return 0;
}

1 REPLY 1

Both the prescaler and the counter count from zero to the value set to PSC/ARR *inclusive*, e.g. if you set PSC to 101, it would count 0, 1, 2, ... 99, 100, 101, 0, 1, 2, ... it means it "divides" by 102.

So you effectively divided 100MHz/102/12 = 81.7kHz, close to what you've measured.

Set PSC to 99 and ARR to 9.

JW