// 4-digit 7-seg increment on button press (COMMON ANODE)
// Segments: D2..D9 (a,b,c,d,e,f,g,dp), Digits: D10..D13 (DIG1..DIG4), Button: A0 (INPUT_PULLUP)

const uint8_t segPins[8]   = {2,3,4,5,6,7,8,9};   // a,b,c,d,e,f,g,dp
const uint8_t digitPins[4] = {10,11,12,13};       // DIG1..DIG4 (common anode: HIGH = ON)

const uint8_t digitPatterns[10][7] = {
  {1,1,1,1,1,1,0}, //0
  {0,1,1,0,0,0,0}, //1
  {1,1,0,1,1,0,1}, //2
  {1,1,1,1,0,0,1}, //3
  {0,1,1,0,0,1,1}, //4
  {1,0,1,1,0,1,1}, //5
  {1,0,1,1,1,1,1}, //6
  {1,1,1,0,0,0,0}, //7
  {1,1,1,1,1,1,1}, //8
  {1,1,1,1,0,1,1}  //9
};

volatile unsigned int numberToDisplay = 0; // 0..9999

// Button (INPUT_PULLUP)
const uint8_t buttonPin = A0;
int lastButtonReading = HIGH;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50UL; // ms
int buttonStateStable = HIGH;

void setup() {
  // segments as outputs
  for (uint8_t i = 0; i < 8; ++i) pinMode(segPins[i], OUTPUT);
  // digit control pins as outputs
  for (uint8_t i = 0; i < 4; ++i) pinMode(digitPins[i], OUTPUT);
  // turn all digits OFF (LOW for CA)
  for (uint8_t i = 0; i < 4; ++i) digitalWrite(digitPins[i], LOW);

  // button input with internal pull-up
  pinMode(buttonPin, INPUT_PULLUP);

  // initialize segments to OFF (for CA: HIGH = OFF)
  for (uint8_t i = 0; i < 8; ++i) digitalWrite(segPins[i], HIGH);
}

void displayOneDigit(uint8_t whichDigitPin, uint8_t num) {
  // Turn OFF all digits first (LOW for CA)
  for (uint8_t i = 0; i < 4; ++i) digitalWrite(digitPins[i], LOW);

  // Set segments for 'num' — NOTE: for COMMON ANODE, segment LOW = ON
  for (uint8_t s = 0; s < 7; ++s) {
    if (digitPatterns[num][s]) digitalWrite(segPins[s], LOW);  // ON
    else                      digitalWrite(segPins[s], HIGH); // OFF
  }
  // decimal point left OFF
  digitalWrite(segPins[7], HIGH);

  // Enable this digit (HIGH for CA)
  digitalWrite(whichDigitPin, HIGH);
  delay(3); // short on-time for persistence
  // Disable digit again
  digitalWrite(whichDigitPin, LOW);
}

void loop() {
  // Multiplex refresh - show all 4 digits quickly
  uint8_t thousands = numberToDisplay / 1000;
  uint8_t hundreds  = (numberToDisplay / 100) % 10;
  uint8_t tens      = (numberToDisplay / 10) % 10;
  uint8_t ones      = numberToDisplay % 10;

  displayOneDigit(digitPins[0], thousands);
  displayOneDigit(digitPins[1], hundreds);
  displayOneDigit(digitPins[2], tens);
  displayOneDigit(digitPins[3], ones);

  // Read button and debounce
  int reading = digitalRead(buttonPin);

  if (reading != lastButtonReading) {
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonStateStable) {
      buttonStateStable = reading;
      // button pressed = LOW (because of INPUT_PULLUP)
      if (buttonStateStable == LOW) {
        numberToDisplay++;
        if (numberToDisplay > 9999) numberToDisplay = 0;
      }
    }
  }
  lastButtonReading = reading;
}
