#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Keypad.h>
#define PIR_PIN 13
#define OLED_ADDR 0x3C
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// 初始化 LCD 顯示(兩個 LCD 使用不同 I2C 位址)
LiquidCrystal_I2C lcd1(0x27, 16, 2); // LCD1:帳號密碼輸入
LiquidCrystal_I2C lcd2(0x26, 16, 2); // LCD2:PIR 偵測結果
// 初始化 OLED 顯示
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// 鍵盤設定
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] = {2, 4, 5, 18};
byte colPins[COLS] = {19, 23, 33, 32};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// 預設帳號與密碼
String correctUsername = "1234";
String correctPassword = "5678";
String input = "";
String username = "";
String password = "";
bool enteringUsername = true;
void setup() {
pinMode(PIR_PIN, INPUT);
lcd1.begin(16, 2);
lcd1.backlight();
lcd2.begin(16, 2);
lcd2.backlight();
oled.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR);
oled.clearDisplay();
oled.setTextSize(1);
oled.setTextColor(SSD1306_WHITE);
oled.setCursor(0, 0);
oled.print("System Start");
oled.display();
lcd1.setCursor(0, 0);
lcd1.print("Enter username:");
lcd2.setCursor(0, 0);
lcd2.print("No intrusion");
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9') {
input += key;
} else if (key == 'C') {
input = "";
} else if (key == 'D') {
if (enteringUsername) {
username = input;
input = "";
enteringUsername = false;
lcd1.clear();
lcd1.print("Enter password:");
} else {
password = input;
input = "";
validateLogin();
}
}
// 顯示輸入中內容
lcd1.setCursor(0, 1);
lcd1.print(" "); // 清空第二行
lcd1.setCursor(0, 1);
lcd1.print(input);
}
// PIR 偵測顯示(只更新狀態改變時才清除/更新內容)
static bool previousState = false;
bool motionDetected = digitalRead(PIR_PIN);
if (motionDetected != previousState) {
previousState = motionDetected;
lcd2.clear();
lcd2.setCursor(0, 0);
if (motionDetected) {
lcd2.print("Intrusion");
lcd2.setCursor(0, 1);
lcd2.print("Detected!");
} else {
lcd2.print("No intrusion");
}
}
delay(100);
}
void validateLogin() {
lcd1.clear();
if (username == correctUsername && password == correctPassword) {
lcd1.print("Access granted");
} else {
lcd1.print("Invalid login");
delay(2000);
input = "";
username = "";
password = "";
enteringUsername = true;
lcd1.clear();
lcd1.print("Enter username:");
}
}