Global variable not increasing

#include <Keypad.h>

const byte ROWS = 4; 
const byte COLS = 4; 
int total =0;
char hexaKeys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte rowPins[ROWS] = {9, 8, 7, 6}; 
byte colPins[COLS] = {5, 4, 3, 2}; 

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); 

void setup(){
  Serial.begin(9600);
}
  
void loop(){
  int customKey = customKeypad.getKey();
  
  if (customKey==49){
    total++;
    Serial.println(total);
  }
}

i am facing a problem where the total global variable is not increasing to more than 1 when I press a key on the keypad.

  • What key does this happen with ?
  • Show us your wiring.

Works for me. Might be power/wiring resetting the sketch.

If you drop your code into keypad-input.ino - Wokwi ESP32, STM32, Arduino Simulator simulation (from wokwi-membrane-keypad Reference | Wokwi Docs)

...it counts up on the '1' button fine:

1
2
3
4
5
6
1 Like

This should happen with any key i press.

  • Tell use what this does ?
if (customKey==49){

update if 1 is pressed on the keypad

So did you test the code with pressing '1' or just any key?
try again and now press the ONE many times

i tried but did not work!

The value (total) automatically turns to 0 .
if 1 is pressed continuously then only it increases.
any solution?

???

That looks exactly like what the code is written to do.

What do you intend it to do?

The value of total automatically turns to 0.
increasing the value to 10,after 2 or 5 sec it automatically turns to zero.

Please add the line to setup()

void setup(){
  Serial.begin(9600);
 Serial.println("Reset");
}

and test again
Show the output of the Serial Monitor while you pressing the various keys

2 Likes

This is the output

Your board restarted while you pressed some keys.
It seems that your connection to the keyboard is incorrect (short circuit)

1 Like

means the usb port is not working properly?
but the power led in arduino is not turning off even for a second ?

NO
I meant the connection to your arduino keypad.

The USB has nothing to do with the issue

meaning that the wire are not loosy?

Since the Arduino only runs setup() once per powerup/reset, the repeated "RESET" means that something must be resetting the board. Maybe there's some loose wire somewhere connecting power to ground or something pushing the red RESET button on the Uno?

ok, thanks

  • In the future, do not edit your previous post.
2 Likes