This is a short version of my code, that I am using currently.
#include <avr/sleep.h>
#include <Keypad.h>
#include <SPI.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define powerPin0 0
#define interruptPin 2
#define redLED A0
#define greenLED A1
#define Password_Length 8
char enteredPassword [Password_Length];
unsigned long int userPassword;
byte data_count = 0;
byte led_blink = 0;
bool wokeUP = true;
bool blinking = true;
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
const long interval = 60000;
const byte ROWS = 4;
const byte COLS = 3;
char hexaKeys[ROWS][COLS] = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
{'*', '0', '#'}
};
byte rowPins[ROWS] = {3, 4, 2, 6};
byte colPins[COLS] = {7, 8, 9};
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(powerPin0, OUTPUT);
digitalWrite(powerPin0, HIGH);
lcd.init();
lcd.backlight();
}
void loop() {
Buzzer(); // 2 buzzer sounds when system starts
lcd.setCursor(0, 0);
lcd.print("Code");
char customKey = customKeypad.getKey();
if (customKey) {
previousMillis = currentMillis;
enteredPassword[data_count] = customKey;
lcd.setCursor(data_count, 1);
lcd.print(enteredPassword[data_count]);
digitalWrite(greenLED, HIGH);
delay(50);
digitalWrite(greenLED, LOW);
data_count++;
}
if (data_count == Password_Length - 1) {
lcd.clear();
delay(100);
userPassword = atol(enteredPassword);
if (userPassword == 1234567) {
lcd.setCursor(0, 0);
lcd.print("OK");
delay(1000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Going to");
lcd.setCursor(0, 1);
lcd.print("Sleep");
delay(1000);
Going_To_Sleep();
led_blink = 0;
clearData();
lcd.init();
lcd.clear();
} else {
lcd.setCursor(0, 0);
lcd.print("Wrong");
delay(1000);
lcd.clear();
clearData();
}
}
if (wokeUP == true) { // call sleep function if inactive for 1 minute
systemInactiveSleep();
}
}
void Buzzer() {
if (blinking) {
while (led_blink < 2) {
digitalWrite(greenLED, HIGH);
delay(50);
digitalWrite(greenLED, LOW);
delay(50);
led_blink++;
}
blinking = false;
}
}
void systemInactiveSleep() {
currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
Going_To_Sleep();
led_blink = 0;
clearData();
lcd.init();
lcd.clear();
}
}
void clearData() {
wokeUP = true;
currentMillis = millis();
previousMillis = millis();
while (data_count != 0) {
enteredPassword[data_count--] = 0;
}
return;
}
void Going_To_Sleep() {
sleep_enable();
attachInterrupt(0, wakeUp, LOW);
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
delay(1000);
digitalWrite(greenLED, LOW);
pinMode(interruptPin, INPUT_PULLUP);
pinMode(9, OUTPUT);
digitalWrite(9, LOW);
digitalWrite(powerPin0, LOW);
sleep_cpu();
}
void wakeUp() {
sleep_disable();
detachInterrupt(0);
blinking = true;
digitalWrite(9, INPUT);
digitalWrite(powerPin0, HIGH);
}