0
\$\begingroup\$

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?

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Is encVal recognized as a global outside the routine? \$\endgroup\$
    – Andy aka
    Dec 1 '20 at 14:17
  • \$\begingroup\$ 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? \$\endgroup\$
    – ocrdu
    Dec 1 '20 at 14:24
  • 1
    \$\begingroup\$ 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). \$\endgroup\$ Dec 1 '20 at 14:33
  • 1
    \$\begingroup\$ Maybe show more code \$\endgroup\$
    – Mike
    Dec 1 '20 at 14:35
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ Dec 1 '20 at 14:39
5
\$\begingroup\$

This line:

int encVal = 0;

Creates a variable local to the ISR.

If you expect that variable name to be globally accessible then you could have problems.

Even if you have declared a global variable by that name, the local version of encVal will be changed inside the ISR and then will be discarded when the ISR returns.

As Peter comments, in the global declaration it should be declared with the volatile keyword so the compiler knows it may change at any time (changed by the ISR, in this case).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.