/*Lab1: keypad -> servo, irremote, temperater and humidity sensor -> LCD*/
//Libraries
#include <Keypad.h>
#include <Servo.h>
#include <IRremote.h>
#include <dht.h>
#include <LiquidCrystal_I2C.h>
//Constants
#define SERVO_PIN 9
#define DHT22_PIN A3
#define RECV_PIN 12
LiquidCrystal_I2C lcd(0x27, 16, 2);
dht DHT;
Servo doorServo;
// Setup the 4x4 keypad
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {7, 6, 5, 4};
byte colPins[COLS] = {3, 2, 1, 0};
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();
lcd.setBacklight(HIGH);
}
void loop()
{
get_Key();
receiveSignal();
readDHT22();
}
//unlock door
void unlockDoor() {
Serial.println("Door Unlocked");
doorServo.write(90);
}
// lock door
void lockDoor() {
Serial.println("Door Locked");
doorServo.write(0);
}
//Get key in keypad
void get_Key() {
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);
}
}
}
//receive signal from remote
void receiveSignal() {
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
}
}
//read hum and temp
void readDHT22() {
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.
}