#define LATCH 2
#define CLOCK 3
#define DATA 4

#define NES 0
#define SNES 1

static uint8_t stored_bits[2], bits, mask, index;
bool data_state, controller_type;

void setup() {
  //initiate controller type
  controller_type = SNES;
  switch (controller_type) {
    case NES:
      bits = 8;
      break;
    case SNES:
      bits = 16;
      break;
  }
  
  //initiate pin input
  pinMode(LATCH, OUTPUT);
  pinMode(CLOCK, OUTPUT);
  pinMode(DATA, INPUT_PULLUP);
  
  Serial.begin(115200);

  digitalWrite(CLOCK, HIGH);
  digitalWrite(LATCH, HIGH);

  delay(5);
}

void loop() {
  //SET LATCH
  digitalWrite(LATCH, LOW);
  delayMicroseconds(12);
  digitalWrite(LATCH, HIGH);
  stored_bits[0] = 0;
  stored_bits[1] = 0;
  mask = 0x80;
  index = 0;
  
  //SAMPLE BITS
  for (uint8_t set_bit = 0; set_bit < bits; set_bit++) {
    delayMicroseconds(6);
    digitalWrite(CLOCK, LOW);
    if (index == 1 && mask <= 0x08) data_state = 0;
    else data_state = !digitalRead(DATA);
    stored_bits[index] |= data_state *mask;
    delayMicroseconds(6);
    digitalWrite(CLOCK, HIGH);
    mask >>= 1;
    if (!mask) {
      mask = 0x80;
      index++;
    }
  }
  
  delay(15);
  
  //DEBUG
  switch (controller_type) {
    case NES:
      for (mask = 0x80; mask > 0x00; mask >>= 1) {
        if(stored_bits[0] & mask) Serial.print(1); else Serial.print(0);
      }
      Serial.println();
      break;
    case SNES:
      for (mask = 0x80; mask > 0x00; mask >>= 1) {
        if(stored_bits[0] & mask) Serial.print(1); else Serial.print(0);
      }
      Serial.print(" ");
      for (mask = 0x80; mask > 0x00; mask >>= 1) {
        if(stored_bits[1] & mask) Serial.print(1); else Serial.print(0);
      }
      Serial.println();
      break;
  }
}
74HC165
74HC165
D0D1D2D3D4D5D6D7GNDLOGIC