zvodd
9/15/2015 - 7:34 PM

SnesTest.ino.c


//**************************************************************//
//  Name    : SnesTest.ino                                      //
//  Author  : zv_odd                                            //
//  Date    : 3 Sep, 2015                                       //
//  Version : 1.0                                               //
//  Notes   : Snes Controller Serial Output Tester              //
//****************************************************************


//define where your pins are
const int dataPin = 9;  // RED
const int latchPin = 8; // YELLOW
const int clockPin = 7; // BLUE

long buttonData, lastButtonData = 72;  //01001000

// On NES Controller there are only 8 buttons, also B, Y swap to A and B
const int n_buttons = 12;
char* buttons[] = {"B", "Y", "SELECT", "START",
                   "UP", "DOWN", "LEFT", "RIGHT",
                   "A", "X", "L_BUTTON", "R_BUTTON"}; 

void setup() {
  //start serial
  Serial.begin(9600);

  //define pin modes
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT); 
  pinMode(dataPin, INPUT);
}

void loop() {
  // Latch Signal
  digitalWrite(latchPin, HIGH);
  delayMicroseconds(12);
  digitalWrite(latchPin, LOW);
  
  int temp = 0;
  buttonData = 0;
  for (int i = 0; i < n_buttons; i++)
  {
    digitalWrite(clockPin, LOW);
    delayMicroseconds(0.2);
    temp = digitalRead(dataPin);
    // 0 Indicates button depressed for SNES controller
    if (!temp) {
      //temp = size_buttonData - i;
      buttonData = buttonData | ((long)1 << i);
    }
    digitalWrite(clockPin, HIGH);
  }

  if (buttonData != lastButtonData){ 
    lastButtonData = buttonData;
    // Print Raw Value of Registers
    Serial.println(buttonData, BIN);
  
    // Print String in Button Name Array
    for (int n = 0; n < n_buttons; n++)
    {
      if (buttonData & (1 << n) ){
        Serial.print(buttons[n]);
        Serial.print(", ");
      }
    }
    Serial.println("\n-------------------");
  }
  delay(10);
}