Changeable password lock system

Hi, can anyone help me on this. I need to make the password length to be 6 digit long but I fail to make it even I had define in the beginning. Below is my code. Thanks.

#include <TMRpcm.h>
#include <Servo.h>
#include <Keypad.h>
#include <EEPROM.h>
#include <SD.h>                           //include SD module library                     
#include <SPI.h>          
#define SD_ChipSelectPin 53
TMRpcm tmrpcm;

const byte numRows= 4;          //number of rows on the keypad
const byte numCols= 4;          //number of columns on the keypad

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

char keypressed;//Where the keys are stored it changes very often
char code[]= {'1','2','3','4','5','6'};  //The default code, you can change it or make it a 'n' digits one

char code_buff1[sizeof(code)];  //Where the new key is stored
char code_buff2[sizeof(code)];  //Where the new key is stored again so it's compared to the previous one

short k=0,i=0,s=0,j=0;          //Variables used later

byte rowPins[numRows] = {32,30,28,26}; //Rows 0 to 3 //if you modify your pins you should modify this too
byte colPins[numCols]= {24,22,7,6}; //Columns 0 to 3

int mode = 0;
int doorSens = A1;
Keypad myKeypad= Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);
Servo lock;                               //定义LED控制引脚
#define buzzer A2 

void setup()
{
    pinMode(A1,INPUT_PULLUP);
    pinMode(doorSens, INPUT_PULLUP);
    tmrpcm.speakerPin = 9; 
    Serial.begin(9600);                        //配置9600
    Serial.println("STANBY!");  
    lock.attach(A3);
    pinMode(A3,OUTPUT);
    lock.write(0);

    
                      
          for(i=0 ; i<sizeof(code);i++)
          {        //When you upload the code the first time keep it commented
            EEPROM.get(i, code[i]);             //Upload the code and change it to store it in the EEPROM
          }   
             
           
     if (!SD.begin(SD_ChipSelectPin)) 
     {      //see if the card is present and can be initialized
        Serial.println("SD fail");
        return;                               //don't do anything more if not
     }
     else
     {
      Serial.println("sucess");
     }
}


void loop()
{
   myKeypad.addEventListener(keypadEvent);
   myKeypad.getKey();
    
  keypressed = myKeypad.getKey(); 
  
    if(keypressed == '*')
    {
            delay(500);
            Serial.println("Enter code");
            GetCode();                          //Getting code function
                  if(k==sizeof(code))
                   openDoor();
                  else
                  {
                    Serial.println("Wrong passowrd");
                  
                  }
            delay(1000);
            Serial.println("Stanby!");
          
    }

     if(keypressed == '#')
     {
      delay(500);
      ChangeCode();
      delay(1000);
      Serial.println("Stanby!");                 //When done it returns to standby mode
     }


         
}

void keypadEvent(KeypadEvent eKey) 
{
  switch (myKeypad.getState()) {
    case PRESSED:

      Serial.print("Enter:");
      Serial.println(eKey);
      playsound();
      }
}

void playsound()
{
  tone(buzzer, 131);
  delay(200);
  noTone(buzzer);
}

void GetCode(){                  //Getting code sequence
       i=0;                      //All variables set to 0
       k=0;
       //j=0; 
                                     
     while(keypressed != 'A')
     {                                     //The user press 0 to confirm the code otherwise he can keep typing
           keypressed = myKeypad.getKey();                         
            if(keypressed != NO_KEY && keypressed != 'A' )
            {       //If the char typed isn't A and neither "nothing"
              //Serial.println(j,1);                                  //This to write "*" on the LCD whenever a key is pressed it's position is controlled by j
             // Serial.println("*");
              //j++;
            if(keypressed == code[i]&& i<sizeof(code))
            {            //if the char typed is correct a and i increments to verify the next caracter
                 k++;                                              //Now I think maybe I should have use only a or i ... too lazy to test it -_-'
                 i++;
            }
            else
            {
                k--;   
          
            }
            //if the character typed is wrong a decrements and cannot equal the size of code []
            }
     }
            
    keypressed = NO_KEY;

}


void ChangeCode(){                      //Change code sequence
      Serial.println("Changing code");
      delay(1000);
      Serial.println("Enter old code");
      GetCode();                      //verify the old code first so you can change it
      
            if(k==sizeof(code))
            {      //again verifying the a value
            Serial.println("Changing code");
            GetNewCode1();            //Get the new code
            GetNewCode2();            //Get the new code again to confirm it
            s=0;
              for(i=0 ; i<sizeof(code) ; i++){     //Compare codes in array 1 and array 2 from two previous functions
              if(code_buff1[i]==code_buff2[i])
              s++;                                //again this how we verifiy, increment s whenever codes are matching
              }
                  if(s==sizeof(code)){            //Correct is always the size of the array
                  
                   for(i=0 ; i<sizeof(code) ; i++){
                  code[i]=code_buff2[i];         //the code array now receives the new code
                  EEPROM.put(i, code[i]);        //And stores it in the EEPROM
                  
                  }
                  Serial.println("Code Changed");
                  delay(2000);
                  }
                  else{                         //In case the new codes aren't matching
            
                  Serial.println("Code not match");
           
                  delay(2000);
                  }
            
          }
          
          else{                     //In case the old code is wrong you can't change it
          Serial.println("Wrong");
          delay(2000);
          }
}

void GetNewCode1(){                      
  i=0;
  //j=0;
  Serial.println("Enter a new code and press A");
  delay(2000);
             
         while(keypressed != 'A'){            //A to confirm and quits the loop
             keypressed = myKeypad.getKey();
               if(keypressed != NO_KEY && keypressed != 'A' ){
                //Serial.println(j,0);
                //Serial.println(ekey);
                code_buff1[i]=keypressed;     //Store caracters in the array
                i++;
                //j++;              
                }
                }
keypressed = NO_KEY;
}

void GetNewCode2(){                         //This is exactly like the GetNewCode1 function but this time the code is stored in another array
  i=0;
  //j=0;
  
  Serial.println("Confirm code and press A");;
  delay(2000);

         while(keypressed != 'A'){
             keypressed = myKeypad.getKey();
               if(keypressed != NO_KEY && keypressed != 'A' ){
               //Serial.println(j,0);
               //Serial.println("*");
               //Serial.println("nothing");
                code_buff2[i]=keypressed;
                i++;
                //j++;             
                }
                }
keypressed = NO_KEY;
}

void openDoor()
{             //Lock opening function open for 3s

  Serial.println("Door open"); 
  lock.attach(A3);
  lock.write(90);
  delay(1000);
  lock.detach();
  
  
  while(digitalRead(doorSens)){
    Serial.println("waiting for the action");  
  }
  closeDoor();
 
}

void closeDoor(){
  
  delay(1000);
  lock.attach(A3);
  lock.write(0);
  delay(1000);
  lock.detach();
 
  
}

void speaker()//open door
{
  if (SD.begin(SD_ChipSelectPin))
  {
     tmrpcm.quality(1);
     tmrpcm.setVolume(5);                    //0 to 7. Set volume level
     tmrpcm.play("1.wav"); 
  }
  
}

void speaker1()//close door
{
  if (SD.begin(SD_ChipSelectPin))
  {
     tmrpcm.quality(1);
     tmrpcm.setVolume(5);                    //0 to 7. Set volume level
     tmrpcm.play("3.wav"); 
  }
  
}

void speaker2()//wrong password
{
  if (SD.begin(SD_ChipSelectPin))
  {
     tmrpcm.quality(1);
     tmrpcm.setVolume(5);                    //0 to 7. Set volume level
     tmrpcm.play("2.wav"); 
  }
  
}

What steps would one take to replicate the error?

You have included a LOT of code that is not relevant to the problem. Can you simplify your code so that only the essential parts are included?

That should not be a problem. Ignore that.

sizeof(code)

code_buff1 and code_buff2 are being declared as fixed values, they are not dynamically allocated. If you want the code length to be exactly 6 digits you can just declare char code_buff1[6] no?

But what I am saying is- at what point in the code are you encountering a problem? And what happens specifically?

To clarify that @peterjin I'm not doubting the ability of our members to resolve this problem, I'm trying to give the OP some guidance on how they can address issues like this in future - by focussing on the parts of their code that are relevant to the issue.

When I compile there is no error, logically it should work. Because the char code there, I have put it 6 digits. And the sizeof(code) is depends on how much digits that I had insert. It's true?

Alright understood, but others is just the sub function which are the requirements in my project. The focus point would be the char code

You generally use sizeof when you don't already know the size of the thing, for example when the user enters a value, or the value is determined programmatically. It is also used when dynamically allocating memory with malloc. They probably just used sizeof so code_buff would be the correct length if someone changed the default code.

But in this case, the sizeof call will return 6 every time.

But in this case, the sizeof call will return 6 every time, as it is being declared as a global variable. The allocated length of code_buff1 and code_buff2 in memory will always be 6, even if you later try to put fewer chars into it.

If you put in say 4 chars, the last two chars will be whatever was previously in that memory location. In C++ , I believe this will be just 0's for global variables. (That is 0x00, not ASCII "0")

So, what I need to use instead of sizeof?

I refer to this link but I not understand what it said for change the password length. Keypad Door Lock with Changeable Code - Arduino Project Hub

image

Well, it should say "You can change a 4 digits code to a 6 digits code"...

But he is saying the same thing I said above. He only used sizeof to make it easier for you to change the length. That should not be having an affect on the code not working.

Are you saying it works correctly when you use a 4 digit code? Like this:

image

But it does not work when you do this?:

image

Because it should work either way. The second way is the same as doing this:

image

If you are saying that is not working... Then tell us how it is failing? What happens when you run it?

Yes. It doesnt working when I put 6 digit as u mentioned. When I run it, I enter the 6 digits passcode and it shows password incorrect.

@peterjin

Ok so in the code where it is telling you it is the wrong value, make it print out to Serial the value you entered, as well as the one it is comparing it to. See exactly why it is failing.

Go byte by byte so you can see the true value of each char (and then use ASCII table to lookup).

Something like this:

image

So basically use the serial monitor as a debugger. Add print statements to show you every value of every variable whenever they change. You should be able to find the problem pretty fast.

Good night for now.

Alright. Thanks. I have solved the problem. Thanks alot