title: Reading STM32 timer value
body: <p>I am using a STM32F103 chip and I am trying to configure and use one of the timers. I have used STM32CubeMX to generation code which initializes Timer 2. I start the timer by calling HAL_TIM_Base_Start. Then, in a loop, I print out the current timer value via a call to htim2.Instance->CNT, or alternately by calling the macro __HAL_TIM_GetCounter (which I believe just returns the same value). However, no matter what I do, the count value shows up as zero. I have also tried calling __TIM2_CLK_ENABLE() at the beginning, but it makes no difference.</p>
  
  <p>I have searched for a solution and have found a couple of questions about this issue, but have not found the solution.</p>
  
  <p>Does anyone know what I am doing wrong?</p>
  
  <p>Thanks.</p>
  
  <p>Here is the routine that initializes the timer. This code was generated by STM32CubeMX and I have not modified it:</p>
  
  <pre><code>/* TIM2 init function */
  static void MX_TIM2_Init(void)
  {
  
    TIM_ClockConfigTypeDef sClockSourceConfig;
    TIM_MasterConfigTypeDef sMasterConfig;
  
    htim2.Instance = TIM2;
    htim2.Init.Prescaler = 0;
    htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
    htim2.Init.Period = 0;
    htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
    htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
    if (HAL_TIM_Base_Init(&amp;htim2) != HAL_OK)
    {
      _Error_Handler(__FILE__, __LINE__);
    }
  
    sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
    if (HAL_TIM_ConfigClockSource(&amp;htim2, &amp;sClockSourceConfig) != HAL_OK)
    {
      _Error_Handler(__FILE__, __LINE__);
    }
  
    sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
    sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
    if (HAL_TIMEx_MasterConfigSynchronization(&amp;htim2, &amp;sMasterConfig) != HAL_OK)
    {
      _Error_Handler(__FILE__, __LINE__);
    }
  
  }
  </code></pre>
  
  <p>Then in the main I attempt to start the timer and attempt to print out it's value. This is the code that I use to do that:</p>
  
  <pre><code>__TIM2_CLK_ENABLE();;
  HAL_TIM_Base_Start(&amp;htim2);
  
  while (true)
  {
      Serial.println((long) __HAL_TIM_GetCounter(&amp;htim2));
      delay(100);
  }
  </code></pre>
  
  <p>The 'Serial' class is a class that I wrote which communicates with my PC via a USB serial port.</p>