So I'm in the middle of making a whack-a-mole game, where the heads popping up are LEDs turning on and instead of a hammer there is a button next to each LED. I am testing it through the serial monitor for easy development rignt now and it seems to work fine, but after a while it does some strange things. It stops randomly, the delay it is doing doesn't correspond with the delay that was chosen and printed,...
this is my code:
int leds[10] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
int button12 = A1;
int button12State;
int prevButton12State;
int randLed; int randDuration;
int randInterval;
int currentTargetLed;
String income;
bool pressed;
unsigned long startMillis;
unsigned long ledStartMillis;
void setup() {
Serial.begin(9600);
Serial.setTimeout(200);
for(int i = 0; i < 10; i++) {
pinMode(leds[i], OUTPUT);
}
Serial.println("RESET");
randomSeed(analogRead(A0));
startMillis = millis();
}
void loop() {
// button12State = analogRead(button12);
// if(button12State > 0) {
// if(button12State < 10) {
// Serial.println("button 2 is pressed");
// }
// else if(20 < button12State < 30) {
// Serial.println("button 1 is pressed");
// }
// }
manageLeds();
}
void manageLeds() {
randInterval = random(1000, 5000);
Serial.println("Waiting " + String(randInterval) + " ms");
startMillis = millis();
while((millis() - startMillis) != randInterval) {
// wait for rand interval, don't do anything in the meantime (BUT YOU COULD!)
}
raiseLed();
}
void raiseLed() {
randLed = random(10);
randDuration = random(1000, 5000);
// turn on randomly selected led
digitalWrite(leds[randLed], 1);
Serial.println("turned on led " + String(randLed));
currentTargetLed = randLed;
pressed = false;
// while the les is on for the random duration, check if the button next to it is pressed
ledStartMillis = millis();
while((millis() - ledStartMillis) != randDuration) {
// test without buttons
if(Serial.available() > 0) {
income = Serial.readString();
if(income == String(currentTargetLed)) {
Serial.println("WIN");
digitalWrite(leds[randLed], 0);
Serial.println("turned off led " + String(randLed));
pressed = true;
// don't continue with the set duration when right button pressed
break;
}
}
// test with buttons
}
// print lose message when failed
if(!pressed) {
Serial.println("LOSE");
digitalWrite(leds[randLed], 0);
Serial.println("turned off led " + String(randLed) + " after " + String(randDuration) + " ms");
}
}
some of it isn't used at the moment due to testing through the Serial monitor.
Anyone see what could be causing my problems?