#include <Keypad.h>
#include <TM1637.h>

const uint8_t COLS = 3;
const uint8_t ROWS = 4;

const int sensorPin = 11;
const int ledPinRed = 13;
const int ledPinBlue = 12;

const int interval = 500; 

unsigned long currentMillis = 0;
unsigned long prevTime = 0; 

bool alarmState = false;
bool turnOn = false;

int  createPasswordFlag = 0;

String password;
String offPassword;
const int maxLength = 4;

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

uint8_t  rowPins[ROWS] = {8, 7, 6, 5};
uint8_t  colPins[COLS] = {4, 3, 2};

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

TM1637 tm(9, 10);

void setup() {
  pinMode(sensorPin, INPUT);
  pinMode(ledPinRed, OUTPUT);
  pinMode(ledPinBlue, OUTPUT);

  tm.init();
  tm.set(BRIGHT_TYPICAL);

  Serial.begin(9600);
}

void loop() {
  key = keypad.getKey();
  currentMillis = millis();
  
  if (key != NO_KEY) { 
    if (key == '*')
      createPasswordFlag = 1;
    else if (createPasswordFlag == 1)
      createPassword(key);

  }

  if (digitalRead(sensorPin) == HIGH && turnOn == true) 
    alarmState = true;
  else 
    alarmState = false;
  
  if (currentMillis - prevTime >= interval && alarmState == true) {
    prevTime = currentMillis;
    
    digitalWrite(ledPinRed, !digitalRead(ledPinRed));
    digitalWrite(ledPinBlue, !digitalRead(ledPinRed));
  }
}

void createPassword(char key) {
    int length = password.length();
    if (length < maxLength) {
      password.concat(key);  
      tm.display(length, key - '0');
    } 
    else {
      createPasswordFlag = 0;
      //tm.clearDisplay();
    }
}

void inputPassword(char key) {
  int length = password.length();
  if (length < maxLength) {
      password.concat(key);  
      tm.display(length, key - '0');
    } 
}
uno:A5.2
uno:A4.2
uno:AREF
uno:GND.1
uno:13
uno:12
uno:11
uno:10
uno:9
uno:8
uno:7
uno:6
uno:5
uno:4
uno:3
uno:2
uno:1
uno:0
uno:IOREF
uno:RESET
uno:3.3V
uno:5V
uno:GND.2
uno:GND.3
uno:VIN
uno:A0
uno:A1
uno:A2
uno:A3
uno:A4
uno:A5
keypad1:R1
keypad1:R2
keypad1:R3
keypad1:R4
keypad1:C1
keypad1:C2
keypad1:C3
rgb1:R
rgb1:COM
rgb1:G
rgb1:B
pir1:VCC
pir1:OUT
pir1:GND
4-Digit Display
sevseg1:CLK
sevseg1:DIO
sevseg1:VCC
sevseg1:GND