// --------------------------------------------------------------------------------
/*

23 密碼鎖

[學習重點]

1. 認識 KeyPad

[挑戰]

- 自行按需要改良程式


Created by Jason on 23 Aug 2022.

*/
// --------------------------------------------------------------------------------

// KeyPad

#include <Keypad.h>

const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
  { '1', '2', '3', 'A' },
  { '4', '5', '6', 'B' },
  { '7', '8', '9', 'C' },
  { '*', '0', '#', 'D' }
};

uint8_t colPins[COLS] = { 5, 4, 3, 2 }; // Pins connected to C1, C2, C3, C4
uint8_t rowPins[ROWS] = { 9, 8, 7, 6 }; // Pins connected to R1, R2, R3, R4

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

// LED
int redPin = 12;
int greenPin = 11;

// Servo
int servoPin = 10;

String password = "A123";
int lock_state = 1;
String key_in;

void setup() {
  Serial.begin(9600);

  // LED
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);

  // Servo
  pinMode(servoPin, OUTPUT);
}

void loop() {
  char key = keypad.getKey();

  if (lock_state > 0) {
    digitalWrite(greenPin, LOW);
    digitalWrite(redPin, HIGH);
    servoPulse(servoPin, 0);
  } else {
    digitalWrite(greenPin, HIGH);
    digitalWrite(redPin, LOW);
    servoPulse(servoPin, 90);
  }

  if (key != NO_KEY) {
    key_in = key_in + key;
    Serial.println(key);
    if (key_in == password) {
      lock_state = -1;
    } else if (key_in.length() > 3) {
      Serial.println("Password Not Correct!");
      key_in = "";
    }
    if (key == '*') {
      Serial.println("Reset");
      key_in = "";
    }
  }
}

void servoPulse (int servo, int angle) {
  int pwm = (angle*11) + 500; // Convert angle to microseconds
  digitalWrite(servo, HIGH);
  delayMicroseconds(pwm);
  digitalWrite(servo, LOW);
}