#include <SPI.h>

#define btndebounce 100

#define led 2
// Define Connections to 74HC165

// Define Connections to 74HC165
#define load    25         // PL pin 1 
#define clock   26         // CP pin 2
#define dataIn  27         // Q7 pin 9

// Define Connections to 74HC595
#define latch     32         // PL pin 1 
#define dataOut   33         // Q7 pin 9


uint32_t lastSwitchPress = 0;
uint32_t CurrentSwitchPress = 0;
uint32_t outputsUpdate = 0;



void setup()
{

  // Setup Serial Monitor
  Serial.begin(115200);

  // Setup 74HC165 & 74HC595 connections
  pinMode(load, OUTPUT);
  pinMode(clock, OUTPUT);
  pinMode(dataIn, INPUT);
  pinMode(latch, OUTPUT);
  pinMode(dataOut, OUTPUT);
  pinMode(led,OUTPUT);
  digitalWrite(led,HIGH);
}

void loop()
{

  SN74165Control();
  


}



void SN74165Control() {
  CurrentSwitchPress = millis();
  if (CurrentSwitchPress - lastSwitchPress > btndebounce) {
    // Write pulse to load pin
    digitalWrite(load, LOW);
    digitalWrite(load, HIGH);

    // Get data from 74HC165

    uint16_t incoming = shift16In(dataIn, clock, MSBFIRST);

    // Print to serial monitor
    if (incoming > 0) {
      outputsUpdate = outputsUpdate^incoming;
      digitalWrite(latch, LOW);
      shift16Out(dataOut, clock, MSBFIRST, outputsUpdate);
      digitalWrite(latch, HIGH);
      Serial.print("Pin States:\r\n");
      Serial.println(outputsUpdate, BIN);
    }
    lastSwitchPress = CurrentSwitchPress;
  }
}


uint16_t shift16In(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
    uint16_t value = 0;
    uint8_t i;

    for(i = 0; i < 16; ++i) {
        if(bitOrder == LSBFIRST)
            value |= digitalRead(dataPin) << i;
        else
            value |= digitalRead(dataPin) << (15 - i);
        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
    return value;
}

void shift16Out(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint16_t val) {
    uint16_t i;

    for(i = 0; i < 16; i++) {
        if(bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (15 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}
74HC165
74HC165
74HC595
74HC595