TIM2 configuration issues - frozen at 0

Post here first, or if you can't find a relevant section!
Post Reply
mkals
Posts: 4
Joined: Thu Jan 13, 2022 11:55 am

TIM2 configuration issues - frozen at 0

Post by mkals »

Hello,

I want to configure a hardware timer such as TIM2 on my STM32L051C8 (https://www.st.com/en/microcontrollers- ... 051c8.html), but cannot make it start counting. TIM2->CNT always stays at 0. I have used CubeMX to generate the HAL configuration to initialize the timer, and have tried including that in my .ino sketch like this:

Code: Select all


TIM_HandleTypeDef htim2;

static void MX_TIM2_Init(void)
{

  /* USER CODE BEGIN TIM2_Init 0 */

  /* USER CODE END TIM2_Init 0 */

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

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 2;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 65535;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
  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();
  }
  /* USER CODE BEGIN TIM2_Init 2 */

  /* USER CODE END TIM2_Init 2 */

}

void setup() {
  
  Serial.begin(115200);
  Serial.println("awake");
  
  pinMode(PA13, OUTPUT);
  digitalWrite(PA13, HIGH);

  MX_TIM2_Init();
}


void loop() {
  Serial.println(String(millis()) + " " + String(TIM2->CNT) + " " + String(TIM21->CNT) + " " + String(SysTick->VAL));
}
The output this produces is like this:

Code: Select all

11410 0 0 29787
11411 0 0 22539
11411 0 0 15128
11412 0 0 18606
11416 0 0 1246
11417 0 0 26157
11417 0 0 18719
11417 0 0 30836
11422 0 0 5182
11422 0 0 30018
11423 0 0 22580
I'm using Arduino_Core_STM32 version 2.2.0.

Any suggestions as to what I am doing wrong?
ABOSTM
Posts: 60
Joined: Wed Jan 08, 2020 8:40 am
Answers: 7

Re: TIM2 configuration issues - frozen at 0

Post by ABOSTM »

Hi @mkals,
Yes, it is normal: CubeMX generates static initialisation code, but you miss the dinamic part of code to start the timer.
Something like:

Code: Select all

HAL_TIM_Base_Start(&htim2);
That being said, there is an alternative of using STM32 HAL to get a timer running:
Have a look at New HardwareTimer stm32duino library
https://github.com/stm32duino/wiki/wiki ... er-library
Post Reply

Return to “General discussion”