Electronic – STM32F103 – Starting timers at the same time

microcontrollerstm32timer

I am using an STM32F103 board (Blue Pill), and I have a simple application where I need to have two pulses on different pins.

I achieve this using Timer3 and Timer4 configured with PWM output on two channels (one each). The problem is that the timers do not start at the same time, and they have an offset of about 3 µs. The main clock is running at 28 MHz.

In the code, changing the order of these two lines will determine what timer starts first (which one is ahead with 3 µs of the other):

  HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
  HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_2);

Is there something I can do? To be noted that in the same program I have Timer1 set up as Capture Compare No Output, and Timer2 to generate a 1.4 MHz clock in the same manner as Timer3 and Timer4.

Later Edit. The called function in the HAL driver:

HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
{
  /* Check the parameters */
  assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));

  /* Enable the Capture compare channel */
  TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);

  if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
  {
    /* Enable the main output */
    __HAL_TIM_MOE_ENABLE(htim);
  }

  /* Enable the Peripheral */
  __HAL_TIM_ENABLE(htim);

  /* Return function status */
  return HAL_OK;
}

Best Answer

The best way of doing this will be by using timer synchronization. See section 15.3.15 of the STM32F1 reference manual.

Set TIM3 to "Enable" master mode (MMS field of TIM3_CR2), and set TIM4 to "Trigger mode" slave mode with trigger ITR2 (TS and SMS fields of TIM4_SMCR). If you've configured everything properly, starting TIM3 will also simultaneously start TIM4.

(There is probably some way of doing this using the HAL, but I'm not familiar enough with it to say what that might be.)