#define dataPin  10
#define latchPin 11
#define clockPin 12

int data = 0b00000000;
int previous_data = 0b00000000;

void setup() {
  Serial.begin(115200);

  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);
  digitalWrite(latchPin, LOW);

  // Set the initial state of the first 8 channels
  updateOutput();

  // Set input pins with pull-up resistors
  for (int i = 2; i <= 9; i++) {
    pinMode(i, INPUT_PULLUP);
  }

  // Set output pin for indication
  pinMode(13, OUTPUT);
}

void loop() {
  readInput();
  checkAndUpdate();
}

void readInput() {
  data = 0; // Reset data

  // Read input pins and set corresponding bits in data
  for (int i = 2; i <= 9; i++) {
    if (digitalRead(i) == LOW) {
      data |= (1 << (i - 2)); // Set the corresponding bit
      digitalWrite(13, HIGH); // Indicate that a button is pressed
    }
  }
}

void checkAndUpdate() {
  if (data != previous_data) { // If there's a change in input data
    updateOutput(); // Update the output
    previous_data = data; // Update previous_data
  }
}

void updateOutput() {
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, data); // Send the data to the shift register
  shiftOut(dataPin, clockPin, MSBFIRST, 0); // Send 0 to ensure 16 bits are shifted out
  digitalWrite(latchPin, HIGH);
}
74HC595
74HC595