// https://wokwi.com/projects/361477000001335297
// https://forum.arduino.cc/t/whack-a-mole-game/1112219
// odd values. nmust be the circuit or something
// const int button_values[] = {913, 429, 267, 179, 110};
// wokwi test values
const int button_values[] = {850, 680, 510, 340, 170,};
// for the analog regions corresponding to buttons
const unsigned char inputPin[2] = {A0, A1};
const int btn_tol = 20;
unsigned long now; // everyone's time for the whole loop
void setup()
{
Serial.begin(115200);
xprintf("\nhello world.\n");
}
void loop()
{
now = millis();
scanButtons();
reportButtons();
}
// stores state and time for debouncing
// and sets pressed for any buttons that get pressed.
unsigned char lastButton[2][5];
unsigned long lastButtonTime[2][5];
unsigned char pressed[2][5];
unsigned char gotPressed(unsigned char thePlayer, unsigned char theButton)
{
return pressed[thePlayer][theButton];
}
// look at all the buttons, load the pressed array
void scanButtons()
{
unsigned long now = millis();
for (unsigned char player = 0; player < 2; player++) {
int analogValue = analogRead(inputPin[player]);
for (int ii = 0; ii < 5; ii++) {
pressed[player][ii] = 0; // false. not pressed - or is it? let us see:
if (now - lastButtonTime[player][ii] < 15) // too soon to look at this button again?
continue;
unsigned char button = (analogValue < button_values[ii] + btn_tol) && (analogValue > button_values[ii] - btn_tol);
if (button != lastButton[player][ii]) {
pressed[player][ii] = button;
lastButton[player][ii] = button;
lastButtonTime[player][ii] = now;
}
}
}
}
// show any pressed buttons
void reportButtons()
{
for (unsigned char player = 0; player < 2; player++) {
for (int ii = 0; ii < 5; ii++) {
if (gotPressed(player, ii)) {
xprintf("player %d detect hit on button %d\n", player, ii);
}
}
}
}
// programmer misses printf...
void xprintf(const char *format, ...)
{
char buffer[256];
va_list args;
va_start(args, format);
vsprintf(buffer, format, args);
va_end(args);
Serial.print(buffer);
}