Hello and good morning
Here comes the "slimmed down" sketch for your pinball machine.
What is made:
- packed all pins into arrays
- declaration and definition of a structure for the buttons
- added a timer to debounce the buttons
// BLOCK COMMENT
// ATTENTION: This Sketch contains elements of C++.
// https://www.learncpp.com/cpp-tutorial/
// https://forum.arduino.cc/t/score-counter-for-pinball-machine/909522
#define ProjectName "Score counter for pinball machine"
// CONSTANT DEFINITION
// you may need to change these constants to your hardware and needs.
constexpr byte Input_[] {A0, A1}; // portPin o---|button|---GND
constexpr byte Output_[] {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // portPin o---|220|---|LED|---GND
constexpr unsigned long ButtonScanTime {20};
// VARIABLE DECLARATION AND DEFINTION
enum {NEWgamepin , OVERpin};
unsigned long currentTime;
struct BUTTON { // a button has a ....
byte name_;
byte pin;
bool state_;
} buttons[] { // the following buttons are initialized
{NEWgamepin, Input_[NEWgamepin], false}, // new game button and
{OVERpin, Input_[OVERpin], false}, // and over button
};
struct TIMER { // a timer has
unsigned long duration;
unsigned long stamp;
};
TIMER buttonScan{ButtonScanTime, 0}; // the buttonScan timer is initialized
// FUNCTIONS
bool checkTimer(TIMER & time_) { // generic time handler using TIME struct
if (currentTime - time_.stamp >= time_.duration ) {
time_.stamp = currentTime;
return true;
} else return false;
}
void setup() {
Serial.begin(9600);
Serial.println(F("."));
Serial.print(F("File : ")), Serial.println(__FILE__);
Serial.print(F("Date : ")), Serial.println(__DATE__);
Serial.print(F("Project: ")), Serial.println(ProjectName);
pinMode (LED_BUILTIN, OUTPUT);
for (auto Input : Input_) pinMode(Input, INPUT_PULLUP);
for (auto Output : Output_) pinMode(Output, OUTPUT);
// check outputs
for (auto Output : Output_) digitalWrite(Output, HIGH);
delay(1000);
for (auto Output : Output_) digitalWrite(Output, LOW);
}
void loop () {
currentTime = millis();
digitalWrite(LED_BUILTIN, (currentTime / 500) % 2);
if (checkTimer(buttonScan)) {
for (auto &button_ : buttons) {
bool stateNew = !digitalRead(button_.pin);
if (button_.state_ != stateNew) {
button_.state_ = stateNew;
if (stateNew) {
static int number = 0;
switch (button_.name_) {
case NEWgamepin:
Serial.println("NEWgamepin");
number = 0;
for (auto Leds : Output_) digitalWrite(Leds, LOW);
break;
case OVERpin:
Serial.println("OVERpin");
digitalWrite (Output_[number], HIGH);
number++;
number = number % (sizeof(Output_) / sizeof(Output_[0]));
if (!number) for (auto Leds : Output_) digitalWrite(Leds, LOW);
break;
}
}
}
}
}
}
Have a nice day and enjoy coding in C++.