1
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0,0);

}

void loop() {
  uint8_t buttons = lcd.readButtons();
  int a;  
  if (buttons) {

    lcd.clear();
    lcd.setCursor(0,0);

    if (buttons & BUTTON_UP) {
      a+= 1;
      lcd.setCursor(0,0);
      lcd.print(a);
    }
  }

I am trying to make a counter that increments everytime the button UP is pressed. Currently, all it is doing is printing 1 everytime the button is pressed. Any help would be nice! Thanks!

  • Try "static int a = 0;" – Mikael Patel Apr 4 '17 at 21:16
  • It has to do with int a;. There's no "starting point" of what a is. – KingDuken Apr 4 '17 at 23:10
5

Your code, simplified, is:

void loop()
    int a;
    a += 1;
}

The problem here is that, by putting the declaration of your counter variable within the loop() function, you've made it local to that function. Every time loop() is called, a new variable a is created, initialized to zero, and then incremented.

You want to move the declaration outside of loop(), creating a global variable that will remain in existence and maintain its value after loop() exits, so that the value is still there when loop() is called again:

int a = 0;
void loop() {
    a += 1;
}

(This could also be done with a static variable, but that's probably beyond the scope of this question.)

-2

all it is doing is printing 1 everytime the button is pressed.

make variable a static, or global.

  • Someone asking a question like this probably doesn't know what a "static" or "global" variable is; explaining that and giving an example is probably what he needs. – cjs Apr 5 '17 at 3:35

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.