// pulse coder
// https://wokwi.com/projects/395389818314203137
// this is designed to translate distinct button presses (as per
// a pinball rolling over a switch) into pulses for ingestion into
// of multiple plibball machines output into a derby-race display conteoller.
// 
// See the https://wokwi.com/projects/395283077096057857 display controller.

// With this setup, more complicated button-handling within pinball 
// machines could be inside each pinball machine and then deliver a
// series of pulses to the display controller

const int pins[] = {6, 7, 8, 9, 10};
const byte NumPins = sizeof(pins)/sizeof(pins[0]);
const byte Active = LOW;
const byte weights[NumPins] = {1, 2, 3, 2, 1};
const byte SignalPin = 3;
const uint16_t PinInterval = 10;
const int PulseInterval = 300;

byte pulses = 0;
uint32_t now, pinLastMs[NumPins];
byte pinStateLast[NumPins];


void setup() {
  int ii = 0;
  for (auto pin : pins) {
    pinMode(pin, INPUT_PULLUP);
    pinStateLast[ii] = digitalRead(pin);
    pinLastMs[ii] = 0;
    ++ii;
  }
  pinMode(SignalPin, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  now = millis();
  checkPins();
  sendSignals();
}

void checkPins(void) {
  int ii = 0;
  for (auto pin : pins) {
    int pinState = digitalRead(pin);
    if (pinState != pinStateLast[ii] && now - pinLastMs[ii] > PinInterval) {
      pinStateLast[ii] = pinState;
      pinLastMs[ii] = now;
      if (pinState == Active) {
        pulses += weights[ii];
        Serial.print("pin");
        Serial.print(pin); Serial.print(":+"); Serial.print(weights[ii]); Serial.print(" ");
      }
    }
    ++ii;
  }
}

void sendSignals(void) {
  static uint32_t last = 0;
  static int lastState = LOW;
  if (pulses > 0 && now - last > PulseInterval) {
    last = now;
    lastState = lastState == LOW ? HIGH : LOW; // toggle
    digitalWrite(SignalPin, lastState);
    //Serial.print("pulses:"); Serial.print(pulses);
    //Serial.print("LED:");
    //Serial.print(lastState); Serial.print(" ");
    if(lastState == LOW){
      --pulses;
    }
  }
}

Pushbuttons into pulses. for Derby race pinball machines