/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// NintendoSpy Firmware for Arduino
// v1.0.1
// Written by jaburns
//
// SNES controller only!

#define PIN_READ(pin) (PIND&(1<<(pin)))
#define WAIT_FALLING_EDGE(pin) while(!PIN_READ(pin)); while(PIN_READ(pin));

#define ZERO  '\0'
#define ONE    '1'
#define SPLIT '\n'

unsigned char rawData[16];

void setup() {
  PORTD = 0x00;
  DDRD  = 0x00;
  PORTC = 0xFF;
  DDRC  = 0x00;
  Serial.begin(115200);
}

void read_shiftRegister() {
  unsigned char *rawDataPtr = rawData;
  unsigned char bits = 16;

  WAIT_FALLING_EDGE(3);
  do {
    WAIT_FALLING_EDGE(5);
    *rawDataPtr = !PIN_READ(7);
    ++rawDataPtr;
  }
  while (--bits > 0);
}

inline void sendRawData() {
  for (unsigned char i = 0; i < 16; i++) {
    Serial.write(rawData[i] ? ONE : ZERO);
  }
  Serial.write(SPLIT);
}

void loop() {
  noInterrupts();
  read_shiftRegister();
  interrupts();
  sendRawData();
}
