//Libraries
#include <dht.h> // sensor lib from https://www.ardumotive.com/how-to-use-dht-22-sensor-en.html
#include <LiquidCrystal_I2C.h> // i2c LCD lib from https://www.ardumotive.com/i2clcden.html
#include <Keypad.h>
#include <Servo.h>
#include <IRremote.h>
dht DHT;
Servo doorServo;
//Constants
#define SERVO_PIN 9
#define DHT22_PIN A3
#define RECV_PIN 12
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Setup the 4x4 keypad
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
uint8_t rowPins[ROWS] = {7, 6, 5, 4};
uint8_t colPins[COLS] = {3, 2, 1, 0};
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Variables
String enteredCode = "";
const String correctCode = "8888"; // door unlock code
IRrecv irrecv(RECV_PIN);
decode_results results;
float hum; //Stores humidity value
float temp; //Stores temperature value
void setup()
{
Serial.begin(9600);
// Setup servo
doorServo.attach(SERVO_PIN);
// Start with door locked
Serial.println("Door Lock System Initialized");
lockDoor();
// Start IR receiver
irrecv.enableIRIn();
Serial.println("IR Receiver is ready and waiting for input...");
// Start LCD
lcd.init();
lcd.backlight();
}
void loop()
{
char key = keypad.getKey();
if (key) { // If a key is pressed
Serial.print("Key Pressed: ");
Serial.println(key);
if (key == '#') { // '#' to check entered code
if (enteredCode == correctCode) {
Serial.println("Correct Code! Door Unlocked.");
unlockDoor();
delay(5000); //delay door open for 5s
lockDoor();
} else {
Serial.println("Incorrect Code. Try Again.");
}
enteredCode = ""; // Reset the code after checking
} else {
enteredCode += key; // Append the pressed key to the entered code
Serial.print("Current Code: ");
Serial.println(enteredCode);
}
}
if (irrecv.decode(&results)) { // Check if a signal is received
Serial.print("IR Code received: ");
Serial.println(results.value, HEX); // Print the received value in HEX
irrecv.resume(); // Receive the next value
}
int chk = DHT.read22(DHT22_PIN);
//Read data and store it to variables hum and temp
hum = DHT.humidity;
temp = DHT.temperature;
//Print temp and humidity values to LCD
lcd.setCursor(0, 0);
lcd.print("Humidity: ");
lcd.print(hum);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(temp);
lcd.println("Celcius");
delay(2000); //Delay 2s between temperature/humidity check.
}
//unlock door
void unlockDoor() {
Serial.println("Door Unlocked");
doorServo.write(90);
}
// lock door
void lockDoor() {
Serial.println("Door Locked");
doorServo.write(0);
}