0

I use an STM32F microcontroller on the Keil. I have a problem on while or for loops. The shared code is my faulty section. My for or while loop does not work. I stayed "step = 2" and "counter = 0". I tryed released and debug mode. Debug mode I saw this results watch screen; step = 1 (WaitData = 1) after systemtick increase after that systemtick = 5000 after that step = 2 (systemtick = 0 waitdata = 0) but code stack on the for loop.

#include "stm32f4xx_hal.h"
#include <stdio.h>
#include <stdlib.h>

int step = 0;
int waitdata = 0;
int systemtick1 = 0;
int counter = 0;
void HAL_SYSTICK_Callback(void)
{
    if (WaitData == 1)
    {
        systemtick1++;
        if (systemtick1 == 5000)
        {
            step = 2;
            systemtick1 = 0;
            WaitData = 0;
        }
    }
}

int main(void)
{
    HAL_Init();
    SystemClock_Config();
    MX_GPIO_Init();
    HAL_Delay(2000);
    step = 1;
    WaitData = 1;

    for (; WaitData==1 ; ) // Or while (WaitData == 1);
    {
        asc++;
    }

    step = 3;
    while (1)
    {
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
O.Blue
  • 137
  • 7

1 Answers1

2

The variables you are changing in interrupt needs to be set as volatile, because you don't know how the compiler will optimize it.

The access to the variables is mostly done in sequential, predictable way. But interrupt isn't predictable; therefore you need to use volatile to be able to change the variable outside of the normal "program" flow.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michal D
  • 109
  • 15