I need to make use of 2 buttons, 2 leds and a display to make a 4 digit code that unlocks a safe . One of the buttons as Input and the other-confirm.
When I press the input button for the first time both LEDs switch on and then off to indicate that the app is started then a new sequence starts.
1 push of the button changes the number to 1, two to 2, etc. Each time I press the button one of the pins is turned on and when confirm is pressed the other turns on and saves the number.
When all four numbers are entered the safe either switches to green LED for opened and red for Wrong code.
If possible I also want to make it so that I can manually set the code using the input. I am at the very very beginner stage and I've been trying for hours to get it working somehow using simple code. I read some stuff about arrays but no success so far. Here is my code, it is kind of a mess, I also tried using a for to execute the first action but then I realized it is always on.
If possible suggest solutions, fixes, optimizes for the code, advisable changed, I am also allowed to add extra stuff into the program. Thank you beforehand and much appreciated
#include "Display.h"
// constants who do not change, they specify pins:
const byte buttonConfirm = 8, buttonInput = 9;
const byte ledRed = 4, ledGreen = 5;
int counter = 0;
int lastState = 0;
int pass[4] = {1, 3, 1, 3};
int codeTyped[4] {NULL, NULL, NULL, NULL};
int startUp = 1;
void setup() {
Serial.begin(9600); //begin serial monitor / (9600) serial speed
pinMode (buttonInput, INPUT_PULLUP);
pinMode (buttonConfirm, INPUT_PULLUP);
pinMode (ledRed, OUTPUT);
pinMode (ledGreen, OUTPUT);
Serial.println("Initialized!"); // send state
}
void loop() {
int buttonState = digitalRead(buttonInput);
int buttonSave = digitalRead(buttonConfirm);
while (startUp > 0 && buttonState == LOW) {
digitalWrite(ledRed, HIGH);
digitalWrite(ledGreen, HIGH);
delay(1000);
digitalWrite(ledRed, LOW);
digitalWrite(ledGreen, LOW);
startUp--;
}
// Start of code for safe -----------------------------------------------------------------------
if (buttonState != lastState) {
if (buttonState == LOW) {
digitalWrite(ledGreen, HIGH);
delay(500);
digitalWrite(ledGreen, LOW);
counter = counter + 1;
Display.show(counter);
Serial.println(counter);
}
delay(50);
lastState = buttonState;
}
if (buttonSave == LOW) {
if (counter != pass[0]) {
digitalWrite(ledRed, HIGH);
delay(500);
digitalWrite(ledRed, LOW);
} else {
codeTyped[0] = 1;
digitalWrite(ledGreen, HIGH);
delay(500);
digitalWrite(ledGreen, LOW);
counter = 0;
for(int i = 0; i < 4; i++)
{
Serial.println(codeTyped[i]);
}
Display.show(codeTyped);
}
}
// constrain(counter, 1, 4);
if(counter == 4) counter = 0; //set max numbers to 4, incorrect because I still see 5 and a fast switch to 0
}