#define AMOUNT_IC   1 // amount of used 74HC165 chips
#define DATA_WIDTH  AMOUNT_IC * 8

#define PIN_PL  5
#define PIN_CE  6
#define Q7  3
#define PIN_CLK 4

unsigned long pinValues, oldPinValues;


int pinLatch = 8;  // verbunden mit ST_CP => latch
int pinClock = 12; // verbunden mit SH_CP => clock
int pinData  = 11; // verbunden mit DS    => data 

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

  pinMode(PIN_PL, OUTPUT);
  pinMode(PIN_CE, OUTPUT);
  pinMode(PIN_CLK, OUTPUT);
  pinMode(Q7, INPUT);
  pinMode(pinLatch, OUTPUT); // Alle Arduino-Pina dienen zur digitalen Ausgabe
  pinMode(pinClock, OUTPUT);
  pinMode(pinData,  OUTPUT);

  digitalWrite(PIN_CLK, LOW);
  digitalWrite(PIN_PL, HIGH);

  pinValues = readShiftRegisters();
  oldPinValues = pinValues;
  
}

void loop() {
  pinValues = readShiftRegisters();
    if (pinValues != oldPinValues) {
        oldPinValues = pinValues;
    }
    delay(1000);  
}

unsigned long readShiftRegisters(){
    long bitVal;
    unsigned long bytesVal = 0;

    digitalWrite(PIN_CE, HIGH);
    digitalWrite(PIN_PL, LOW);
    delayMicroseconds(5);
    digitalWrite(PIN_PL, HIGH);
    digitalWrite(PIN_CE, LOW);

    for (byte i = 0; i < DATA_WIDTH; i++) {
        bitVal = digitalRead(Q7);
        bytesVal |= (bitVal << ((DATA_WIDTH - 1) - i));

        Serial.print(bitVal);
        

        digitalWrite(PIN_CLK, HIGH);
        delayMicroseconds(5);
        digitalWrite(PIN_CLK, LOW);
    }
    Serial.println("");
    Serial.println(bytesVal);

    digitalWrite(pinLatch, LOW);
    shiftOut(pinData, pinClock, MSBFIRST, bytesVal);
    digitalWrite(pinLatch, HIGH);

    return (bytesVal);
}
74HC165
74HC595