Search code examples
arduinouint8tarduino-c++

Arduino check equality of uint8_int


I'm trying to check the equailty of uint8_t type when I press a button on my Arduino shield. I understand the type is an unsigned integer, but the code never enters the if statement even though I get the print statement "Button pressed: 0" Can anyone tell me why?

#include <MFShield.h>

MFShield mfs ;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  mfs.onKeyPress( [](uint8_t button){
    if (button == 0 || button == 0x00 || button == '0')
    {
      Serial.println("working");
    }
    Serial.println("Button pressed: " + String(button)); 
  });
}

void loop() {
  mfs.loop();
} 

Solution

  • As already mentioned in comments

    button == 0 and button == 0x00 are the same thing. So one can be omitted. button == '0' doesn't make sense as '0' is 48. This will never be true in your program.

    From what I see in the source code of the MFShield librarie's source code the described behaviour should not be possible.

    // Keys polling
        if (onKeyPress_func != NULL && time - t_buttons >= MFS_BUTTONS_POLLING_INTERVAL_MS)
        {
            t_buttons = time;
            uint8_t key_mask = 0;
            for (uint8_t i=0; i < 3; i++)
                key_mask |= (!digitalRead(KEY_PIN[i]) << i);
    
            if (key_mask != key_mask_pre)
            {
                if (key_mask != 0)
                {
                    key_mask_pre = key_mask;
                    onKeyPress_func (ffs(key_mask));
                }
                else
                    key_mask_pre = 0;
            }
        }
    

    The code checks all 3 buttons and sets a bit in key_mask for each button pressed.

    The callback function onKeyPress_func you provided is only called when key_mask is unequal 0 and when the key state has changed since last checked.

    So using this code you should never get the print "Button pressed: 0" as you claim. Your button cannot become 0. It is either For the same reason you'll never enter your if statement.