Construct the following circuit:


Enter the following code:

// Constants
const int inc_pin = 2;
const int dec_pin = 3;
const int debounce_delay = 50;  // ms

// Globals
int counter = 0;
int inc_state = HIGH;
int inc_prev = HIGH;
int dec_state = HIGH;
int dec_prev = HIGH;
unsigned long inc_last_debounce = 0;
unsigned long dec_last_debounce = 0;

void setup() {
  pinMode(inc_pin, INPUT_PULLUP);
  pinMode(dec_pin, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {

  // Read the current position of both buttons
  int inc_read = digitalRead(inc_pin);
  int dec_read = digitalRead(dec_pin);

  // Remember when the buttons changed states
  if ( inc_read != inc_prev ) {
    inc_last_debounce = millis();
  }
  if ( dec_read != dec_prev ) {
    dec_last_debounce = millis();
  }

  // Wait before checking the state of the increment button again
  if ( millis() > (inc_last_debounce + debounce_delay) ) {
    if ( inc_read != inc_state ) {
      inc_state = inc_read;
      if ( inc_state == LOW ) {
        counter++;
        Serial.println(counter);
      }
    }
  }

  // Wait before checking the state of the decrement button again
  if ( millis() > (dec_last_debounce + debounce_delay) ) {
    if ( dec_read != dec_state ) {
      dec_state = dec_read;
      if ( dec_state == LOW ) {
        counter--;
        Serial.println(counter);
      }
    }
  }

  // Remember the previous states for next loop()
  inc_prev = inc_read;
  dec_prev = dec_read;
}

Simulator: https://tinkercad.com/things/6pbK8hhQqym