Sergio Castillo
Sergio Castillo

Reputation: 31

How to handle global variables in interrupts

I am a newbie in this of embedded systems. For my final degree project I am developing a system working with a STM NUCLEO Board with a STM32F411RE microcontroller.

In addition, I am working with stmcube32 for loading initialization code.

At this point I am stuck, but first let me explain you a litle background:

So, what is my problem? When debugging, I realise that the program remains stuck in the first statement while (boton_Flag != 2); inside the function above.

It should stay there until I press the BOTON2 to change the flag to value 2 and this way the program keep running. However, when I press the button, in spite of the program JUMPS TO THE INTERRUPT AND CHANGES THE VALUE, when it returns to the function, the value is again 0 (its initialized value).

My conclusion, which may be wrong, is that I am not passing the variable to the function correctly, and the program interpret it as a local variable inside the function, but I am not sure at all.

I hope to have been explained as well as possible, if not, please let me know.

Upvotes: 1

Views: 4609

Answers (1)

Riley
Riley

Reputation: 698

You're right, you aren't passing the variable correctly. The way you have it, when the function is called you create a local variable (local to the function) and assign it the value of your global boton_flag.

There are two ways that you could fix this:
1. Just use the global variable in the function. If it's already global there is no need to pass it to your function.
2. Pass boton_flag by reference. i.e. numeroJugadores(&boton_Flag);. If you do it this way, you'll have a pointer to boton_flag which slightly changes the code in numeroJugadores (you have to dereference boton_flag every time you use it).

Upvotes: 2

Related Questions