Keypad values changing in array! help!

Hello, can someone please help.
I have a keypad and an lcd 20 x 4, I want to store 3 key presses in an array "factoryPresses[2]", I dont understand why when I press the last digit (third one) the counter changes to that keypress and the array stores a weird value. Here is my code and images! Thanks!

image
image

#include <Servo.h>
#include <Keypad.h>
#include <Wire.h> 
#include <LiquidCrystal.h>

Servo servo1;
//rs, en, d4, d5, d6, d7
LiquidCrystal lcd(A0, A1, A2, A3, A4, A5); //pins in the arduino

const int ledOpen = A9;
const int ledClosed = A8;
int pos = 0;
int openDoor = false;
int i = 0;
long factoryPass[2];
int cont = 0;

const byte ROWS = 4; 
const byte COLS = 4; 

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

byte rowPins[ROWS] = {13, 12, 11, 10};   //row pins in the arduino 
byte colPins[COLS] = {9, 8, 7, 6}; //col pins in the arduino


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

void setup() {
  servo1.attach(5);   //attach to pin 5
  lcd.begin(20,4);  // initialize lcd 20 x 4
  
  Serial.begin(9600);
}

void loop() {
  //factory reset pass = 123
  char customKey = customKeypad.getKey();
  lcd.setCursor(0,0); // cursor column 0, line 0
  lcd.print("Factory Reset Key: ");

 if ( i < 3){
   if (customKey){
     factoryPass[i] = customKey - '0'; //converts key press (char) to int
     Serial.println(customKey);
     Serial.print(",");
     Serial.print(factoryPass[i]);
     lcd.setCursor(i,1);
     lcd.print(customKey);
     Serial.print("counter: ");
     Serial.print(i);
     i++;
   }
   //if( i == 2){
     //   int cont = 1;
  // }
 }

//if(cont == 1){  //prints array 1 time
   // Serial.print("here");
    //cont++;
    //for (int j=0; j <= 2; j++){
      //Serial.print(factoryPass[j]);
    //}
  }

long factoryPass[2];
You have two elements in your array here.
factoryPass[0]
factoryPass[1]


if ( i < 3){

You are looking at:
factoryPass[0]
factoryPass[1]
factoryPass[2]

:open_mouth:

Thanks Larry, but why do I only have 2 elements if i have (i < 3) and the keypad indeed only allows 3 presses?

Because you only defined 2 elements.
long factoryPass[2];

Thankyou very much! I thought it went from 0 to 2 ! :slight_smile:

long factoryPass[2];
You are setting aside only two elements
:frowning_face:
factoryPass[0]
factoryPass[1]


We all go thru this
:woozy_face:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.