2023-02-22 03:08 AM
I have an F411 PCB board, for which I want to use timer 1 to generate micro-second delay.
This is the init code:
static void MX_TIM1_Init(void)
{
/* USER CODE BEGIN TIM1_Init 0 */
/* USER CODE END TIM1_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
/* USER CODE BEGIN TIM1_Init 1 */
/* USER CODE END TIM1_Init 1 */
htim1.Instance = TIM1;
htim1.Init.Prescaler = 16-1;
htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
htim1.Init.Period = 65535;
htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim1.Init.RepetitionCounter = 0;
htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim1) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim1, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM1_Init 2 */
/* USER CODE END TIM1_Init 2 */
}
In main function, after init, I start the timer.
MX_TIM1_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_Base_Start(&htim1);
This is my delay function:
void delay_us (uint16_t us)
{
__HAL_TIM_SET_COUNTER(&htim1,0); // set the counter value a 0
while (__HAL_TIM_GET_COUNTER(&htim1) < us); // wait for the counter to reach the us input in the parameter
}
I have a simple test app to verify the delay:
__HAL_TIM_SET_COUNTER(&htim1, 0); // set the counter value a 0
uint32_t prev_t1_tick = __HAL_TIM_GET_COUNTER(&htim1);
HAL_Delay(1);
uint32_t cur_t1_tick = __HAL_TIM_GET_COUNTER(&htim1);
sprintf(log_str, "main while loop %ld ...\r\n", (cur_t1_tick - prev_t1_tick));
HAL_UART_Transmit(&huart2, (uint8_t *)log_str, strlen(log_str), 0xFFFF);
Those few pieces of codes work well: (cur_t1_tick - prev_t1_tick) is always 999 or 1000. That means that timer1 counter goes up by 1 in 1 micro-second. Is it correct?
However, when I tried to add them into my real app, in that delay_us function, the retrieved counter is always 0.
Can anyone tell me what could be the problem?
2023-02-22 05:28 AM
Check in device, if TIM1 runs. Was TIM1 clock enabled in RCC before setting it up?
JW
2023-02-22 04:04 PM
Where could it possibly be? In my app, I use quite a number of interfaces like UART1, 2, SPI 1,2,3,5 and I2C1.
I will check.
2023-02-22 04:37 PM
Check RCC->APB2ENR2 TIM1EN (Bit 0)
Check the enable bit in TIM1->CR1 CEN
Check other TIM1 registers are non-zero