Search code examples
ctimerembeddedstm32

C - Code does not return to main after timer interrurpt


I am using stm32f103 microprossesor on our custom design board. I used timer interrupt for setting a bool variable to true in every 10ms. I check value of the bool variable in the main loop and if this variable is true, I toggle a led on board on every 500ms.

Although, timer interrupt flag cleared after finishing setting true operation, the code does not return to the main loop and led is not toggled. Timer initialize, interrupt and main loop as follows.

static void MX_TIM2_Init(void)
{
  TIM_ClockConfigTypeDef sClockSourceConfig;
  TIM_MasterConfigTypeDef sMasterConfig;

  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 7199;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 99;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  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();
  }

  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
      /* Initialization Error */
      Error_Handler();
  }

  /*##-2- Start the TIM Base generation in interrupt mode ####################*/
  /* Start Channel1 */
  if (HAL_TIM_Base_Start_IT(&htim2) != HAL_OK)
  {
      Error_Handler();
  }
}

void TIM2_IRQHandler(void)
{
  HAL_TIM_IRQHandler(&htim2);
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    task = true;
}

The main loop

while (1)
{
    if(task == true)
    {
        task_timer++;

        if(task_timer % 50 == 0)
        {
            HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_15);
        }
        task = false;
    }
}

When I use else if statement in the main loop, code is processed as expected.

while (1)
{
    if(task == true)
    {
        task_timer++;

        if(task_timer % 50 == 0)
        {
            HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_15);
        }
        task = false;
    }
    else if(task == false)
    {
       ...
    }
}

Interestingly, if I used only else statement, also code works unstable.

Is there anyone can explain the cause of this.

Thanks.


Solution

  • Turn off all compiler optimizations in settings.