5

When working with a microcontroller such as a PIC32MZ is it acceptable to use static variables inside the interrupt? This would be for a time counter. If the interrupt triggers every one msecond and a flag is needed every second.

Also is it necessary to make this variable volatile or its existence inside the interrupt makes it volatile?

3 Answers 3

6

Yes static inside the interrupt routine is not a problem.

Volatile is not required in my opinion because you only access the variable from the isr function.

Sign up to request clarification or add additional context in comments.

Comments

5

If the variable is accessed by both the interrupt and main code then it must be visible to both, either at file scope or globally between files. Declaring the variable as static is not a problem.

With regards to volatile, if you are setting a flag in the interrupt function that is then polled by the main code to detect the occurrence of the interrupt event then you must declare the variable as volatile or you can get what appears as incorrect code operation, but is in fact totally legal.

e.g. waiting in a loop for a flag to be set by the interrupt

while ( !Interrupt_Flag ) { } 

If the variable Interrupt_Flag is not declared volatile then the compiler can read its value just once and either loop forever or skip over the loop without ever entering the loop. If it is declared volatile then the variable will be read on every iteration of the loop.

Just because a variable is used in the interrupt function does not make it volatile.

If you modify the value of the variable in the interrupt function and main code, e.g. set the flag in the interrupt and clear in the main code, then you must remember to disable interrupts around the lines where you modify the value in the main code or strange things will happen.

1 Comment

In general, you don't need the critical section if the access to the variable is atomic, and I can't imagine non-atomic read or write of a flag, unless it is in a bit field, where you need to read and then use bitwise AND/OR to set or clear a single bit.
2

Yes you can use static variable inside Interrupt routine. You also don't need to declare it volatile. For example:

void IRQHandler(){ static uint16_t i=0; if(i>=500){ i=0; }else{ i++; } } 

The line static uint16_t i=0; will only run the first time.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.