const unsigned char hitButton = 2;
const unsigned char hitLED = 3;
const unsigned char cheatLED = 7;
const unsigned char lockedOutLED = 6;
const unsigned char beatingHeartLED = 8;
const unsigned long rechargePeriod = 1000; // resource availability rate
const unsigned long lockoutPeriod = 300; // "gun" cool off period
const unsigned long debouncePeriod = 20; // debounce
const unsigned long flashPeriod = 66; // "hit" lamp stab of light
bool lastReading = HIGH;
// timers
unsigned long lastRecharge;
unsigned long lockoutUntil = -lockoutPeriod;
unsigned long ignoreDebounce;
unsigned long flashUntil;
bool resourceReady = true;
bool flashOn;
void setup() {
pinMode(hitButton, INPUT_PULLUP);
pinMode(hitLED, OUTPUT);
pinMode(cheatLED , OUTPUT);
pinMode(lockedOutLED , OUTPUT);
pinMode(beatingHeartLED , OUTPUT);
Serial.begin(115200);
Serial.println("\npatience is a virtue\n");
}
void loop() {
unsigned long now = millis();
// resource recharge
if (now - lastRecharge >= rechargePeriod) {
if (resourceReady) Serial.println(" MISS");
resourceReady = true;
lastRecharge = now; // not now + recharge!
}
// heartbeatr and nothing more, not synchronized or dependent
digitalWrite(beatingHeartLED, (now & 0x3ff) < 250 ? HIGH : LOW);
if (flashOn)
if (now - flashUntil > flashPeriod) {
digitalWrite(hitLED, LOW);
flashOn = false;
}
else digitalWrite(hitLED, LOW);
// CHEAT!
// this makes it much easier
digitalWrite(cheatLED, resourceReady ? HIGH : LOW);
digitalWrite(lockedOutLED, now - lockoutUntil < lockoutPeriod ? HIGH : LOW);
// too soon to look at switch (bounce)?
if (now - ignoreDebounce < debouncePeriod) return;
// edge detection
bool reading = digitalRead(hitButton);
if (reading != lastReading) {
lastReading = reading;
ignoreDebounce = now; // ignore button for debounce interval
if (reading == LOW) {
if (now - lockoutUntil < lockoutPeriod) {
Serial.println("LOCKED OUT");
lockoutUntil = now; // restart lockout period
return;
}
lockoutUntil = now; // can't ask again during lockout
if (resourceReady) {
flashOn = true;
flashUntil = now;
resourceReady = false;
Serial.println("HIT");
}
else {
Serial.println("TOO EARLY");
}
}
}
}CHEAT ->
AVAILABLE
AUTO ->
LOCKED OUT