I make an electronic safety by arduino nano. I simulated it on Wokwi and it worked as I expected. When I built it and uploaded the code, my lcd sometimes worked but mostly it displayed black boxes or weird characters and could not interact with my keypad anymore. Additionally, my nano could not remember the code when I charged it with other power supplies such as power bank.
Can somebody help me please and thank you for your help.
Here is my code:
#include <Keypad.h>
#include <LiquidCrystal.h>
#include <Servo.h>
//keypad here
const byte rownum= 4;
const byte colnum= 3;
byte rowpins[rownum]= {A0, A1, A2, A3};
byte colpins[colnum]= {8,9,10};
char keys[rownum][colnum]={
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
{'*', '0', '#'}
};
Keypad keypad= Keypad(makeKeymap(keys), rowpins, colpins, rownum, colnum);
//LCD here
LiquidCrystal lcd(2,3,4,5,6,7);
//Servo here
Servo servo;
int pos=90;
//locking code here
String SecretCode= "1236";
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
//setup for lcd
lcd.clear();
lcd.begin(16,2);
//setup for servo
servo.attach(11);
}
void LockScreen(){
lcd.clear();
lcd.setCursor(4,0);
lcd.print("Locking");
delay(2000);
lcd.clear();
lcd.setCursor(2,0);
String entercode="Enter code";
for (byte i=0; i< entercode.length(); i++){
lcd.print(entercode[i]);
delay(50);
}
delay(2000);
lcd.clear();
lcd.setCursor(2,0);
String toverify="# to verify";
for (byte i=0; i< toverify.length(); i++){
lcd.print(toverify[i]);
delay(50);
}
}
void Lock(){
pos=0;
servo.write(pos);
delay(200);
}
void Unlock(){
pos=90;
servo.write(pos);
delay(200);
}
String Enter(){
lcd.setCursor(2,1);
String enter="";
char key=keypad.getKey();
while (key!='#'){
key=keypad.getKey();
if(key >= '0' && key <= '9'){
lcd.print(key);
enter+=key;
}
}
return enter;
}
void Verifying(){
String code=Enter();
delay(500);
lcd.clear();
String verify="Verifying....";
for (byte i=0; i< verify.length(); i++){
lcd.print(verify[i]);
delay(100);
}
delay(2000);
if (code==SecretCode){
lcd.clear();
lcd.print("Unlock Succeed");
Unlock();
delay(3000);
Locking();
} else{
lcd.clear();
lcd.print("ACCESS DENIED");
delay(3000);
}
}
void Locking(){
lcd.clear();
lcd.setCursor(2,0);
lcd.print("* to lock");
char key=keypad.getKey();
while(key!='*'){
key=keypad.getKey();
}
if(key=='*'){
Lock();
}
}
void loop() {
// put your main code here, to run repeatedly:
if (pos==90){
Lock();
} else if (pos==0) {
LockScreen();
Verifying();
}
}
Here is the circuit made on Wokwi.