#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978
#define REST 0
#include <Servo.h>
#include <Bounce2.h>;
#define SHORT_PRESS_TIME 500 // 500 milliseconds
#define LONG_PRESS_TIME 2000 // 2000 milliseconds
#define DOOR_OPEN_TIME 5000 // 2000 milliseconds
int tempo = 120;
// Пины для кнопок
const int buttonPins[4] = {2, 3, 4, 5};
// Пин для светодиода
const int ledPin = 6;
// Пин для пищалки
const int buzzer = 7;
// Пин для сервопривода
const int servoPin = 9;
// Пин для внутренней кнопки
const int insideButtonPin = 10;
int currentIndex; // Какую цифру кода проверяем на правильность
int correctCode[4] = {1, 2, 3, 4}; // Правильный код
int currentCode[4] = {0, 0, 0, 0}; // Код, который сейчас вводим
int newCode[4] = {0, 0, 0, 0}; // Код, на который хотим поменять
int lastButtonEntered = 0;
bool isLocked = true; // Состояние сервопривода
bool isEnteringCode = false; // Вводим ли код
bool isChangingCode = false; // Меняем ли пароль
int codeChangeState = -1; // 0 - Вводим прошлый ПИН, 1 - Вводим новый ПИН 2 - Проверяем новый ПИН
int ledState = LOW; // этой переменной устанавливаем состояние светодиода
long previousMillisLED = 0; // храним время последнего переключения светодиода
long previousMillisSERVO = 0; // храним время последнего переключения сервы
long interval = 1000;
Servo myServo;
Bounce debouncer = Bounce();
Bounce db1 = Bounce();
Bounce db2 = Bounce();
Bounce db3 = Bounce();
Bounce db4 = Bounce();
int melody[] = {
// Dart Vader theme (Imperial March) - Star wars
// Score available at https://musescore.com/user/202909/scores/1141521
// The tenor saxophone part was used
NOTE_A4,4, NOTE_A4,4, NOTE_A4,4, NOTE_F4,-8, NOTE_C5,16,
NOTE_A4,4, NOTE_F4,-8, NOTE_C5,16, NOTE_A4,2,//4
NOTE_E5,4, NOTE_E5,4, NOTE_E5,4, NOTE_F5,-8, NOTE_C5,16,
NOTE_A4,4, NOTE_F4,-8, NOTE_C5,16, NOTE_A4,2,
NOTE_A5,4, NOTE_A4,-8, NOTE_A4,16, NOTE_A5,4, NOTE_GS5,-8, NOTE_G5,16, //7
NOTE_DS5,16, NOTE_D5,16, NOTE_DS5,8, REST,8, NOTE_A4,8, NOTE_DS5,4, NOTE_D5,-8, NOTE_CS5,16,
};
int melody2[] = {
// Cannon in D - Pachelbel
// Score available at https://musescore.com/user/4710311/scores/1975521
// C F
NOTE_FS4,2, NOTE_E4,2,
NOTE_D4,2, NOTE_CS4,2,
NOTE_B3,2, NOTE_A3,2,
};
// sizeof gives the number of bytes, each int value is composed of two bytes (16 bits)
// there are two values per note (pitch and duration), so for each note there are four bytes
int notes = sizeof(melody) / sizeof(melody[0]) / 2;
int notes2= sizeof(melody2) / sizeof(melody2[0] / 2);
// this calculates the duration of a whole note in ms
int wholenote = (60000 * 4) / tempo;
int divider = 0, noteDuration = 0;
void setup() {
// Инициализация пинов
for (int i = 0; i < 4; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(ledPin, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(insideButtonPin, INPUT_PULLUP);
// Даем бибилотеке знать, к какому пину мы подключили кнопку
debouncer.attach(insideButtonPin);
debouncer.interval(5); // Интервал, в течение которого мы не буем получать значения с пина
db1.attach(buttonPins[0]); db1.interval(5);
db2.attach(buttonPins[1]); db2.interval(5);
db3.attach(buttonPins[2]); db3.interval(5);
db4.attach(buttonPins[3]); db4.interval(5);
myServo.attach(servoPin);
myServo.write(0); // Закрыть замок
Serial.begin(9600);
}
void blinkLed(int pin = ledPin) {
unsigned long currentMillis = millis();
//проверяем не прошел ли нужный интервал, если прошел то
if(currentMillis - previousMillisLED > interval) {
// сохраняем время последнего переключения
previousMillisLED = currentMillis;
// если светодиод не горит, то зажигаем, и наоборот
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// устанавливаем состояния выхода, чтобы включить или выключить светодиод
digitalWrite(pin, ledState);
}
}
void loop() {
blinkLed(ledPin);
debouncer.update();
db1.update(); db2.update(); db3.update(); db4.update();
checkInsideButton();
if (!isLocked){
servoControl();
}
if (isLocked && !isChangingCode) {
getCode(0);
}
if (isChangingCode){
getCode(1);
}
if (isEnteringCode) {
int timeSinceLastEnter = millis() - lastButtonEntered;
if (timeSinceLastEnter > 10000){
Serial.println("time elapsed");
isEnteringCode = false;
currentIndex = 0;
}
}
}
void checkInsideButton() {
if (debouncer.rose()) { // button is released
long pressDuration = debouncer.previousDuration();
if ( pressDuration < SHORT_PRESS_TIME ){
Serial.println("short");
unlock();
}
if ( pressDuration > LONG_PRESS_TIME ){
Serial.println("long");
isChangingCode = true;
codeChangeState = 0;
}
}
}
void getCode(int mode) { // mode: 0 - проверка кода для открытия двери, 1 - изменение кода.
int currentButton = 0;
if(db1.fell() || db2.fell() || db3.fell() || db4.fell()){
tone(buzzer, NOTE_E3);
}
if(db1.rose() || db2.rose() || db3.rose() || db4.rose()){
noTone(buzzer);
}
if(db1.fell()){
Serial.println("1");
currentButton = 1;
}
if(db2.fell()){
Serial.println("2");
currentButton = 2;
}
if(db3.fell()){
Serial.println("3");
currentButton = 3;
}
if(db4.fell()){
Serial.println("4");
currentButton = 4;
}
if(currentButton != 0){
currentCode[currentIndex] = currentButton;
currentIndex ++;
if(currentIndex == 4){
if(!mode) openTheDoor();
else changeCode();
currentIndex = 0;
currentCode[0] = 0;
}
lastButtonEntered = millis();
isEnteringCode = true;
Serial.println("enteringCode");
}
}
void openTheDoor(){
if(arrayEquals(currentCode, correctCode)){
Serial.println("Correct");
unlock();
}else{
Serial.println("not Correct");
playSadMusic();
}
}
void changeCode(){
if(codeChangeState == 0){
if(arrayEquals(currentCode, correctCode)){
codeChangeState = 1;
Serial.println("Correct PIN");
}
}
else if(codeChangeState == 1){
for(int i = 0; i < 4; i++){
newCode[i] = currentCode[i];
}
codeChangeState = 2;
Serial.println("new PIN");
}
else if(codeChangeState == 2){
if(arrayEquals(currentCode, newCode)){
codeChangeState = -1;
isChangingCode = false;
for(int i = 0; i < 4; i++){
correctCode[i] = newCode[i];
}
Serial.println("Changed to new PIN");
}
}
}
void unlock() {
previousMillisSERVO = millis();
interval = 200;
isLocked = false;
Serial.println("unlocked");
myServo.write(90);
playHappyMusic();
}
void lock(){
interval = 1000;
isLocked = true;
myServo.write(0);
Serial.println("locked");
}
void playHappyMusic() {
for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) {
// calculates the duration of each note
divider = melody[thisNote + 1];
if (divider > 0) {
// regular note, just proceed
noteDuration = (wholenote) / divider;
} else if (divider < 0) {
// dotted notes are represented with negative durations!!
noteDuration = (wholenote) / abs(divider);
noteDuration *= 1.5; // increases the duration in half for dotted notes
}
// we only play the note for 90% of the duration, leaving 10% as a pause
tone(buzzer, melody[thisNote], noteDuration*0.9);
// Wait for the specief duration before playing the next note.
delay(noteDuration);
// stop the waveform generation before the next note.
noTone(buzzer);
}
}
void playSadMusic() {
tone(buzzer, 392, 500); // Соль
delay(500);
tone(buzzer, 349, 500); // Фа
delay(500);
tone(buzzer, 330, 500); // Ми
delay(500);
noTone(buzzer);
}
void servoControl(){
unsigned long currentMillis = millis();
if(currentMillis - previousMillisSERVO > DOOR_OPEN_TIME) {
lock();
}
}
bool arrayEquals(int* arr1, int* arr2){
bool isC = true;
for(int i = 0; i < 4; i++){
isC = isC && arr1[i] == arr2[i];
}
return isC;
}