#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Keypad.h>
// OLED 設定
#define I2C_MASTER_SCL_IO 10 /*!< gpio number for I2C master clock */
#define I2C_MASTER_SDA_IO 9 /*!< gpio number for I2C master data */
#define OLED_ADDR 0x3C /*!< SSD1306 I2C address */
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// 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] = {21, 20, 19, 18};
byte colPins[COLS] = {17, 16, 15, 14};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// 密碼相關設定
String correctPassword = "1234";
String inputPassword = "";
int attempts = 0;
// 蜂鳴器
#define BUZZER_PIN 13
void setup() {
Serial.begin(115200);
// 初始化 Wire (I2C)
Wire.begin(SDA_PIN, SCL_PIN);
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR, &Wire, -1)) {
Serial.println("SSD1306 初始化失敗!");
for (;;);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("密碼鎖系統啟動");
display.display();
delay(2000);
display.clearDisplay();
// 初始化蜂鳴器
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
}
void loop() {
char key = keypad.getKey(); // 讀取按鍵
if (key) {
handleKeyPress(key);
}
}
void handleKeyPress(char key) {
if (key == '#') { // # 作為確認鍵
if (inputPassword == correctPassword) {
unlock();
} else {
attempts++;
if (attempts >= 3) {
triggerAlarm();
} else {
displayMessage("密碼錯誤!");
}
}
inputPassword = ""; // 清空輸入
} else if (key == '*') { // * 作為清除鍵
inputPassword = "";
displayMessage("密碼已清除");
} else { // 數字鍵輸入
inputPassword += key;
updatePasswordDisplay();
}
}
void updatePasswordDisplay() {
display.clearDisplay();
display.setCursor(0, 0);
display.print("輸入密碼: ");
for (size_t i = 0; i < inputPassword.length(); i++) {
display.print("*"); // 顯示星號代替密碼
}
display.display();
}
void unlock() {
display.clearDisplay();
display.setCursor(0, 0);
display.println("密碼正確!系統解鎖");
display.display();
digitalWrite(BUZZER_PIN, HIGH);
delay(1000);
digitalWrite(BUZZER_PIN, LOW);
delay(2000);
attempts = 0; // 重置錯誤次數
}
void triggerAlarm() {
display.clearDisplay();
display.setCursor(0, 0);
display.println("密碼錯誤次數過多!");
display.display();
for (int i = 0; i < 5; i++) {
digitalWrite(BUZZER_PIN, HIGH);
delay(500);
digitalWrite(BUZZER_PIN, LOW);
delay(500);
}
attempts = 0; // 重置錯誤次數
}
void displayMessage(String message) {
display.clearDisplay();
display.setCursor(0, 0);
display.println(message);
display.display();
delay(2000);
}