2
\$\begingroup\$

So I am trying to create a delay using a timer but doesn't seem like it's working as expected.

With a clock of 16MHz and a prescaler of 1, it should take 10us to reach a count of 160 (unless I did something wrong).

static void MX_TIM2_Init(void)
{
    __HAL_RCC_TIM2_CLK_ENABLE();

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 1;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period =  160;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
void Delay() {
    while (1) {
        if(__HAL_TIM_GET_FLAG(&htim2, TIM_FLAG_UPDATE))
        {
            GPIOC->ODR ^= GPIO_PIN_10;
        }
        
    }
}

Capture:

enter image description here

\$\endgroup\$
8
  • \$\begingroup\$ Do you ever clear the flag after it gets set? If not then you're just timing how long your while loop takes to execute. \$\endgroup\$
    – brhans
    Jul 13, 2020 at 17:21
  • \$\begingroup\$ are you referring to auto reload register's value being set? doesn't the value reset to 0 after reaching the max count? \$\endgroup\$
    – MKD
    Jul 13, 2020 at 18:15
  • \$\begingroup\$ No, I'm referring to the TIM_FLAG_UPDATE you're reading with __HAL_TIM_GET_FLAG. Surely you need to clear that in your code after you see it get set by the timer hardware ... ? \$\endgroup\$
    – brhans
    Jul 13, 2020 at 18:50
  • \$\begingroup\$ I see a pulse width of 20us instead of 10us \$\endgroup\$
    – MKD
    Jul 13, 2020 at 18:58
  • 1
    \$\begingroup\$ You're setting htim2.Init.Prescaler = 1;, but the actual prescaler used by the timer is "PSC + 1" (datasheet page 368, section 3.4.11). \$\endgroup\$
    – brhans
    Jul 14, 2020 at 20:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.