# How to share a variable between ISR and main-code?

I'm working on some embedded software and I ran into a problem and I cannot figure out why this block isn't working.

I set up interrupts to for several buttons, including a mechanical encoder. I used breakpoints and debugging to determine the code flow. The block that isn't working as it should is super simple.

uint8_t calcEncoderValue(void)
{
int encVal = 0;

if (gpio_get_pin_level(ENC_A))
{
encVal = 2;
}

if (gpio_get_pin_level(ENC_B))
{
encVal = encVal + 1;
}

return (uint8_t) encVal;
}


The code goes into the first if statement when A is HIGH, but value for encVal remains 0.

Coding doesn't get much simpler than this block, so I'm absolutely stumped. Does anyone have any idea what is going wrong here?

• Is encVal recognized as a global outside the routine? Dec 1 '20 at 14:17
• Are you checking on encVal staying 0 within the function or are you checking a variable encVal outside of the function? In the rest of your code, are you using the value returned by the function, or a global variable encVal that exists outside of the function? Dec 1 '20 at 14:24
• If this is an interrupt routine, where does it return the value to??? Presumably this is a function called by an ISR : the error may lie in the calling ISR. But if this IS the ISR it needs to update something externally visible (and declared volatile). Dec 1 '20 at 14:33
– Mike
Dec 1 '20 at 14:35
• If this is in an ISR, then it is perfectly possible the compiler has optimised it out as it may not apparently be used elsewhere. The volatile keyword is your friend in that case. Dec 1 '20 at 14:39

int encVal = 0;