/********* Pleasedontcode.com **********

	Pleasedontcode thanks you for automatic code generation! Enjoy your code!

	- Terms and Conditions:
	You have a non-exclusive, revocable, worldwide, royalty-free license
	for personal and commercial use. Attribution is optional; modifications
	are allowed, but you're responsible for code maintenance. We're not
	liable for any loss or damage. For full terms,
	please visit pleasedontcode.com/termsandconditions.

	- Project: Strongbox
	- Source Code compiled for: Arduino Mega
	- Source Code created on: 2023-09-17 20:12:25
	- Source Code generated by: Tom

********* Pleasedontcode.com **********/

/********* User code review feedback **********
#### Feedback 1 ####
- complete the code.
********* User code review feedback **********/

/****** DEFINITION OF LIBRARIES *****/
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <Servo.h>
#include <EEPROM.h>

/****** SYSTEM REQUIREMENT 1 *****/
// This is a project to create a strongbox with a keypad (to enter the code), a display (to show the state of strongbox) and a servo (to lock or unlock the door).

/****** SYSTEM REQUIREMENT 2 *****/
// A code number has to be stored in EEPROM (the value is 3478) and used for comparison with the code provided by user.

/****** SYSTEM REQUIREMENT 3 *****/
// At startup, Arduino has to initialize the display showing "Press digit code of 4 numbers:".

/****** SYSTEM REQUIREMENT 4 *****/
// Periodically the system has to wait the code of 4 numbers from keypad. After each number is introduced, add a '*' character on the second row. When the 4 digits are introduced, check if the code is equal to the value saved in EEPROM.

/****** SYSTEM REQUIREMENT 5 *****/
// Save on EEPROM also the state of machine which is composed of 2 states: "DOOR LOCKED" and "DOOR UNLOCKED".

/****** SYSTEM REQUIREMENT 6 *****/
// If the code is equal to EEPROM value and the state is "DOOR LOCKED", unlock the door: drive the servo to 180 degrees, show on display 'DOOR UNLOCKED' for 2 seconds, and change the state to 'DOOR UNLOCKED'.

/****** SYSTEM REQUIREMENT 7 *****/
// If the state is 'DOOR UNLOCKED', write on the display 'Enter 4 digits to lock the door', then wait for 4 digits on the keypad. And at each digit pressed, display a '*' character on the second row of the display.

/****** SYSTEM REQUIREMENT 8 *****/
// After the 4 digits are entered, change the state from 'DOOR UNLOCKED' to 'DOOR LOCKED', save it in EEPROM, drive the servo to 0 degrees, display 'DOOR LOCKED' for 3 seconds, and save the code in EEPROM.

/****** FUNCTION PROTOTYPES *****/
void setup(void);
void loop(void);

/***** DEFINITION OF PWM OUTPUT PINS *****/
const uint8_t servo_PIN_D2 = 2;

/***** DEFINITION OF I2C PINS *****/
const uint8_t display_LCD1602I2C_I2C_PIN_SDA_D20 = 20;
const uint8_t display_LCD1602I2C_I2C_PIN_SCL_D21 = 21;
const uint8_t display_LCD1602I2C_I2C_SLAVE_ADDRESS = 39;

// Define the keypad layout
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {30, 31, 32, 33}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {34, 35, 36, 37}; //connect to the column pinouts of the keypad

// Create an instance of Keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

// Create an instance of Servo
Servo doorServo;

// Define the state of the door
enum DoorState {
  DOOR_LOCKED,
  DOOR_UNLOCKED
};
DoorState doorState = DOOR_LOCKED;

// Define the code length
const int CODE_LENGTH = 4;

// Define the code
const int code[CODE_LENGTH] = {3, 4, 7, 8};

// Define the EEPROM address to store the code
const int CODE_ADDRESS = 0;

// Define the EEPROM address to store the door state
const int STATE_ADDRESS = CODE_ADDRESS + CODE_LENGTH;

// Define the LCD display
LiquidCrystal_I2C lcd(display_LCD1602I2C_I2C_SLAVE_ADDRESS, 16, 2);

void setup(void)
{
  // Initialize the servo pin as output
  pinMode(servo_PIN_D2, OUTPUT);

  // Attach the servo to the pin
  doorServo.attach(servo_PIN_D2);

  // Initialize the display
  lcd.begin(16, 2);

  // Display the initial message
  lcd.print("Press digit code");
  lcd.setCursor(0, 1);
  lcd.print("of 4 numbers:");

  // Read the door state from EEPROM
  int storedState = EEPROM.read(STATE_ADDRESS);
  if (storedState == DOOR_UNLOCKED) {
    doorState = DOOR_UNLOCKED;
    lcd.clear();
    lcd.print("DOOR UNLOCKED");
    delay(2000);
  }
}

void loop(void)
{
  // Check if the door is locked
  if (doorState == DOOR_LOCKED) {
    // Wait for the code to be entered
    displayCodeEntry();
    int enteredCode[CODE_LENGTH];
    for (int i = 0; i < CODE_LENGTH; i++) {
      char key = keypad.waitForKey();
      lcd.setCursor(i, 1);
      lcd.print("*");
      enteredCode[i] = key - '0';
    }

    // Check if the entered code matches the stored code
    bool codeMatch = true;
    for (int i = 0; i < CODE_LENGTH; i++) {
      if (enteredCode[i] != code[i]) {
        codeMatch = false;
        break;
      }
    }

    // If the code matches, unlock the door
    if (codeMatch) {
      unlockDoor();
    }
  } else if (doorState == DOOR_UNLOCKED) {
    // Wait for the code to lock the door
    displayCodeConfirmation();
    int enteredCode[CODE_LENGTH];
    for (int i = 0; i < CODE_LENGTH; i++) {
      char key = keypad.waitForKey();
      lcd.setCursor(i, 1);
      lcd.print("*");
      enteredCode[i] = key - '0';
    }

    // Lock the door and save the code
    lockDoor(enteredCode);
  }
}

// Function to display the code entry prompt on the LCD
static void displayCodeEntry()
{
  lcd.clear();
  lcd.print("Enter 4 digits");
  lcd.setCursor(0, 1);
  lcd.print("to unlock door:");
}

// Function to display the code confirmation prompt on the LCD
static void displayCodeConfirmation()
{
  lcd.clear();
  lcd.print("Enter 4 digits");
  lcd.setCursor(0, 1);
  lcd.print("to lock door:");
}

// Function to unlock the door
static void unlockDoor()
{
  doorServo.write(180);
  lcd.clear();
  lcd.print("DOOR UNLOCKED");
  delay(2000);
  doorState = DOOR_UNLOCKED;
  EEPROM.write(STATE_ADDRESS, doorState);
}

// Function to lock the door
static void lockDoor(int enteredCode[])
{
  doorServo.write(0);
  lcd.clear();
  lcd.print("DOOR LOCKED");
  delay(3000);
  doorState = DOOR_LOCKED;
  EEPROM.write(STATE_ADDRESS, doorState);
  for (int i = 0; i < CODE_LENGTH; i++) {
    EEPROM.write(CODE_ADDRESS + i, enteredCode[i]);
  }
}