//Open topic: Wenn der letzte Button zu lange geklickt werden kann es zu
//übersteuerung kommen
#define RELAY_PIN 13 //13 is the same as the build internal led (LED_BUILTIN)
const uint8_t buttonPins[] = {6, 7, 8, 9, 10, 11, 12};
uint8_t codeSequence[] = {6,5,4};
uint8_t codeIndex = 0;
const int codeLength = sizeof(codeSequence)/sizeof(codeSequence[0]);
const int numberOfButton = sizeof(buttonPins)/sizeof(buttonPins[0]);
void setup() {
Serial.begin(9600);
Serial.print("Number of Buttons: ");
Serial.println(numberOfButton);
Serial.print("Codelength: ");
Serial.println(codeLength);
Serial.print("Code is : ");
for (byte i = 0; i< codeLength; i++) {
Serial.print(codeSequence[i]);
}
Serial.println();
for (byte i = 0; i < numberOfButton; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(RELAY_PIN, OUTPUT); //The LED, later the relay to start the music
}
byte readButtons() {
while (true) {
for (byte i = 0; i < numberOfButton; i++) {
byte buttonPin = buttonPins[i];
if (digitalRead(buttonPin) == LOW) {
return i;
}
}
delay(1);
}
}
void codePassed() {
Serial.print("That is correct. ");
Serial.println("Music starts.");
codeIndex = -1;
digitalWrite(RELAY_PIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(2000);
digitalWrite(RELAY_PIN, LOW); // turn the LED on (HIGH is the voltage level)
}
bool checkUserSequence() {
byte expectedButton = codeSequence[codeIndex];
Serial.print("expected Button: ");
Serial.println(expectedButton);
byte actualButton = readButtons();
Serial.print("Number pushed: ");
Serial.println(actualButton);
if (expectedButton != actualButton) {
if(codeSequence[0]==actualButton) { //If the wrong button is also the start button then start again immediatly and go to the next one
codeIndex = 0;
}
else{
codeIndex =-1;
}
return false;
}
return true;
}
void restartAgain() {
Serial.println("Wrong Code. ");
delay(200);
}
void loop() {
if (!checkUserSequence()) {
restartAgain();
}
if (codeIndex == codeLength-1) {
codePassed();
}
codeIndex++;
delay(300);
}