Skip to content

Instantly share code, notes, and snippets.

@j-mcc1993
Last active January 1, 2016 21:19
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save j-mcc1993/8202522 to your computer and use it in GitHub Desktop.
Arduino Sketch that handles serial communication between NES controller and Arduino
int latch = 7; //signals controller to latch button states
int pulse = 5; //toggle to shift out button states
int data = 9; //data in line
int data_byte; //byte that stores button states
int count[] = {0,0,0,0,0,0,0,0}; //each value stores 1 or 0 indicating whether a key is currently pressed
char keys[] = {'a','b','s','d','u','j','l','r'}; //keyboard keys to be pressed
int tempbit; //iterates over the data_byte to grab each button's state
void setup() {
pinMode(latch, OUTPUT);
pinMode(pulse, OUTPUT);
pinMode(data, INPUT);
//set a clean low signal
digitalWrite(latch, LOW);
digitalWrite(pulse, LOW);
}
void loop() {
//Send 12uS signal to latch button data
digitalWrite(latch, HIGH);
delayMicroseconds(12);
digitalWrite(latch, LOW);
delayMicroseconds(6);
data_byte = B00000000; //initialize each bit as 0, it will be OR-ed with each value shifted in. Those values are in turn shifted
//so they take up one bit of the whole byte
for (int i = 0; i < 8; i++) {
data_byte = data_byte | (digitalRead(data) << i);
digitalWrite(pulse, HIGH);
delayMicroseconds(5);
digitalWrite(pulse, LOW);
delayMicroseconds(5);
}
for (int i = 0; i < 8; i++) {
tempbit = bitRead(data_byte, i);
//if button is pressed and it was not previously pressed, press button and change count to 1
if (tempbit == 0 && count[i] == 0) {
count[i] = 1;
Keyboard.press(keys[i]);
}
//if button was pressed (count = 1) and it isn't anymore, release key and count = 0
else if (tempbit == 1 && count[i] == 1) {
count[i] = 0;
Keyboard.release(keys[i]);
}
}
delay(16);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment