[SOLVED]
Please edit your post to add code tags, as described in "How to use this forum".
jremington:
Please edit your post to add code tags, as described in "How to use this forum".
Yeah, sorry i did it.
Basically it’s a quite simple statemachine, two to be exact, but one is too siple to count really.
#include <Bounce2.h>
const byte confirmPin = 2;
const byte inputPin = 3;
const byte redLed = 4;
const byte greenLed = 5;
const uint16_t heartBeatDistance = 5000;
const uint16_t heartBeatFlash = 50;
const uint16_t redAndGreenDuration = 2000;
const uint16_t greenButtonFlash = 100;
const uint16_t redButtonFlash = 100;
const uint16_t greenSignal = 5000;
const uint16_t redSignal = 5000;
enum {
sIdle,
sNewInput,
sInput,
sInputGreen,
sInputRed,
sEval,
sOk,
sFail,
};
Bounce input, confirm;
byte state = sIdle;
byte codeKeys[4] = { 1, 2, 3, 4 };
byte enteredKeys[4];
byte keyIndex;
void setup() {
Serial.begin(250000);
input.attach(inputPin, INPUT_PULLUP);
confirm.attach(confirmPin, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
}
void loop() {
static uint32_t lastEvent;
uint32_t topLoop = millis();
heartBeat(topLoop);
switch (state) {
case sIdle:
if (input.update() && input.fell()) {
lastEvent = topLoop;
digitalWrite(redLed, HIGH);
digitalWrite(greenLed, HIGH);
state = sNewInput;
}
break;
case sNewInput:
if (topLoop - lastEvent >= redAndGreenDuration) {
lastEvent = topLoop;
digitalWrite(redLed, LOW);
digitalWrite(greenLed, LOW);
state = sInput;
keyIndex = 0;
enteredKeys[keyIndex] = 0;
}
break;
case sInput:
if (input.update() && input.fell()) {
lastEvent = topLoop;
digitalWrite(greenLed, HIGH);
state = sInputGreen;
if (++enteredKeys[keyIndex] > 9) {
enteredKeys[keyIndex] = 0;
}
}
if (confirm.update() && confirm.fell()) {
lastEvent = topLoop;
digitalWrite(redLed, HIGH);
state = sInputRed;
}
break;
case sInputGreen:
if (topLoop - lastEvent >= greenButtonFlash) {
digitalWrite(greenLed, LOW);
state = sInput;
}
break;
case sInputRed:
if (topLoop - lastEvent >= redButtonFlash) {
digitalWrite(redLed, LOW);
if (++keyIndex > 3) {
if (!memcmp(codeKeys, enteredKeys, 4)) {
lastEvent = topLoop;
digitalWrite(greenLed, HIGH);
state = sOk;
} else {
lastEvent = topLoop;
digitalWrite(redLed, HIGH);
state = sFail;
}
} else {
enteredKeys[keyIndex] = 0;
state = sInput;
}
}
break;
case sOk:
if (topLoop - lastEvent >= greenSignal) {
digitalWrite(greenLed, LOW);
state = sIdle;
}
break;
case sFail:
if (topLoop - lastEvent >= redSignal) {
digitalWrite(redLed, LOW);
state = sIdle;
}
break;
}
}
void heartBeat(uint32_t topLoop) {
static uint32_t lastHeartbeat;
if (digitalRead(LED_BUILTIN)) {
if (topLoop - lastHeartbeat >= heartBeatFlash) {
lastHeartbeat = topLoop;
digitalWrite(LED_BUILTIN, LOW);
}
} else {
if (topLoop - lastHeartbeat >= heartBeatDistance) {
lastHeartbeat = topLoop;
digitalWrite(LED_BUILTIN, HIGH);
}
}
}