Thank you so much! Now, my LED has stopped turning red instantly, but the keypad with correct code or when the button is pushed still won't make the LED turn green and the servo move. Here is my code right now:
// C++ code
//#include <Wire.h>
#include <Keypad.h>
#include <Servo.h>
#include <LiquidCrystal_I2C.h>
const int button = A1;//Push Button
int val = 0;
const byte numRows = 4; //number of rows on keypad
const byte numCols = 4; //number of columns on 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'}; //The default code
char check1[sizeof(code)]; //Where the new key is stored
char check2[sizeof(code)]; //Where the new key is stored again so it's compared to the previous one
short x = 0, i = 0, s = 0, y = 0; //Variables used later
byte rowPins[numRows] = {2, 3, 4, 5}; //Rows 0 to 3
byte colPins[numCols] = {6, 7, 8, 9}; //Columns 0 to 3
Keypad myKeypad = Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);
Servo myservo;
#define LEDR 10
#define LEDG 13
#define LEDB 12
void setup()
{
myservo.attach(11);
pinMode(button, INPUT);
pinMode(LEDR, OUTPUT);
pinMode(LEDG, OUTPUT);
pinMode(LEDB, OUTPUT);
myservo.write(0);
digitalWrite(LEDR, LOW);
digitalWrite(LEDG, LOW);
digitalWrite(LEDB, LOW);
}
void Red() {
digitalWrite(LEDR, HIGH);
digitalWrite(LEDG, LOW);
digitalWrite(LEDB, LOW);
}
void Green() {
digitalWrite(LEDR, LOW);
digitalWrite(LEDG, HIGH);
digitalWrite(LEDB, LOW);
}
void Off() {
digitalWrite(LEDR, LOW);
digitalWrite(LEDG, LOW);
digitalWrite(LEDB, LOW);
}
void loop() {
val = digitalRead(button);
if (val == HIGH) { //check if val is high - button is pressed
Green();
OpenDoor();
}
keypressed = myKeypad.getKey(); //Constantly waiting for a key to be pressed
if (keypressed == '*') { // * to open the lock
ReadCode(); //Getting code function
if (x == sizeof(code)) { //The ReadCode function assign a value to a (it's correct when it has the size of the code array)
Green();
OpenDoor();
}
else {
//set led to red for 2 seconds
Red();
delay(2000);
Off();
}
}
}
void ReadCode() { //Getting code sequence
i = 0; //All variables set to 0
x = 0;
y = 0;
while (keypressed != '#') { //The user press A to confirm the code otherwise he can keep typing
keypressed = myKeypad.getKey();
if (keypressed != NO_KEY && keypressed != '*' ) { //If the char typed isn't A and neither "nothing"
// y++;
digitalWrite(LEDR, LOW);
digitalWrite(LEDG, LOW);
digitalWrite(LEDB, HIGH);
if (keypressed == code[i] && i < sizeof(code)) { //if the char typed is correct a and i increments to verify the next caracter
x++;
i++;
}
else
x--; //if the character typed is wrong a decrements and cannot equal the size of code []
}
}
keypressed = NO_KEY;
}
void OpenDoor(){
digitalWrite(LEDR, LOW);
digitalWrite(LEDG, HIGH);
digitalWrite(LEDB, LOW);
myservo.write(90); //
delay (200);
}