I use an STM32F103c8t6. What I want is to measure time between several statements. I found out HAL_getTick does not work since the resolution is too small (1 ms).
However, I cannot seem to initialize the timer correctly. With CubeMX I selected:
TIM2: Slave mode: Trigger mode Trigger Source: ITR0 Clock Source: Internal Clock Rest disabled
And the following code is generated:
/* TIM2 init function */
static void MX_TIM2_Init(void)
{
TIM_ClockConfigTypeDef sClockSourceConfig;
TIM_SlaveConfigTypeDef sSlaveConfig;
TIM_MasterConfigTypeDef sMasterConfig;
htim2.Instance = TIM2;
htim2.Init.Prescaler = 35999;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 35999;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
if (HAL_TIM_OnePulse_Init(&htim2, TIM_OPMODE_SINGLE) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
sSlaveConfig.SlaveMode = TIM_SLAVEMODE_TRIGGER;
sSlaveConfig.InputTrigger = TIM_TS_ITR0;
if (HAL_TIM_SlaveConfigSynchronization(&htim2, &sSlaveConfig) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
}
My own code in the main / while loop:
....
__HAL_RCC_TIM2_CLK_ENABLE();
And later I get the value with
uint32_t value = __HAL_TIM_GET_COUNTER(&htim2);
However, I only see 0's returning from this function.
I wonder if the timer is started at all (I tried to do it very soon after initialization of the timer, but did not make a difference). The timer always has state HAL_TIM_STATE_READY.
How should I start (and possibly restart) the timer?