Electrical – STM32 PWM output frequency is off

hal-librarypwmstm32stm32f4timer

Using an STM32F429I-DISCO board. SYSCLK is set to 180 MHz. I verified the value from MCO2 output pin, and it is spot on. Setting up GPIO_AF3_TIM9 channel 1, and need an output of 12.288 MHz and 50% duty cycle. Calculated config values as:

  const uint32_t TIMF =  180000000;
  const uint32_t TFOUT =  12288000;
  uint16_t ARR = (TIMF / TFOUT) - 1;
  uint16_t uhPrescalerValue =  ((SystemCoreClock) / TIMF) - 1;
  uint16_t pulse = ARR/2 + 1;

Results are prescalar = 0, ARR = 13, pulse = 7.

Here is the setup code:

  GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  GPIO_InitStruct.Speed =  GPIO_SPEED_HIGH;
  GPIO_InitStruct.Alternate = GPIO_AF3_TIM9;
  GPIO_InitStruct.Pin = GPIO_PIN_CHANNEL1;
  HAL_GPIO_Init(GPIOE, &GPIO_InitStruct)

  TimHandle.Instance = TIMx;
  TimHandle.Init.Prescaler =  uhPrescalerValue;
  TimHandle.Init.Period = ARR;
  TimHandle.Init.ClockDivision = 0;
  TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;
  if(HAL_TIM_PWM_Init(&TimHandle) != HAL_OK)
  {
    Error_Handler();
  }

  sConfig.OCMode = TIM_OCMODE_PWM1;
  sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfig.OCFastMode = TIM_OCFAST_DISABLE;
  sConfig.Pulse = pulse;
  if(HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }

Output on scope counter shows PWM frequency as 12.8582 MHz. Duty cycle is correct. Where have I gone wrong in deriving the parameters?

Best Answer

You cannot produce 12.288 MHz by integer division of a 180 MHz source.

The closest you would come would be dividing by 14, which would yield the 12.857 and some following decimals, which is likely within measurement error of what you think you got.

Perhaps you can adjust your goal to use that. Or perhaps you can change the source crystal frequency to something which when multiplied up by the STM32 PLL and divided down will produce your goal more exactly. There are yet more complicated ways of doing this - fractional N synthesizer, etc.

In the end solutions for turning one frequency into another have various power, cost, accuracy and phase noise consequences. To pick one, you'll need to consider your specific requirements in detail.