# STM32F103 - Starting timers at the same time

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;
}

• HAL_TIM_PWM is a library function no? – Trevor_G May 5 '17 at 20:04
• Yes, from the HAL library. – Cezar Chirila May 5 '17 at 20:05
• Check the function then, see if you can add the paramaters, or otherwise change it to set both register bits in the same instruction. – Trevor_G May 5 '17 at 20:07
• It seems strange that the delay between the two is so large. 3us is about 85 clock cycles. Anyway, I edited the main question to have the function inside the driver. Maybe you got an idea? – Cezar Chirila May 5 '17 at 20:23
• I have changed the function above so that first I only enable the capture compare of both. The delay between them is now about 0.7us. Thanks! – Cezar Chirila May 5 '17 at 20:45

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.