const int PIN_DATA  = 4; 
const int PIN_CLK   = 7; 
const int PIN_LATCH = 8; 

byte input165;
byte oInput165;
uint32_t saveMillis;

void setup() {
  Serial.begin(115200);
  pinMode(PIN_DATA, INPUT);
  pinMode(PIN_CLK, OUTPUT);
  pinMode(PIN_LATCH, OUTPUT);
  //digitalWrite(PIN_LATCH, LOW);
  delay(100);
  getInputFrom165(input165);
  oInput165 = ~input165; 
  //saveMillis = millis();

}

void getInputFrom165(byte &inp) {
    //digitalWrite(PIN_LATCH, LOW);
    digitalWrite(PIN_LATCH, HIGH);

    for (byte i = 0; i < 8; i++) {
        bool bit = digitalRead(PIN_DATA);
        bitWrite(inp, 7-i, bit);
        digitalWrite(PIN_CLK, HIGH); // Shift out the next bit
        digitalWrite(PIN_CLK, LOW);
    }
    digitalWrite(PIN_LATCH, LOW);
    
}

void loop() {
  //digitalWrite(PIN_LATCH, LOW);
  if (millis() - saveMillis >= 50) { 
      saveMillis = millis(); 
      getInputFrom165(input165);
  }
  
  //if (millis() - saveMillis >= 50) {
      //saveMillis = millis();
      if (input165 != oInput165) {
          oInput165 = input165;
          Serial.println(input165);
      }
  //}
 
#if(0)
  // Step 1: Sample
  digitalWrite(latchPin, LOW);
  digitalWrite(latchPin, HIGH);

  // Step 2: Shift
  Serial.print("Bits: ");
  for (int i = 0; i < numBits; i++) {
    int bit = digitalRead(dataPin);
    if (bit == HIGH) {
      Serial.print("1");
    } else {
      Serial.print("0");
    }
    digitalWrite(clockPin, HIGH); // Shift out the next bit
    digitalWrite(clockPin, LOW);
  }

  Serial.println();
  delay(1000);
#endif
}
74HC165