Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to read NES controller button presses with an Arduino
/* This code is released into the public domain.
* Pekka Väänänen, 2016 */
/*
http://www.mit.edu/~tarvizo/nes-controller.html
+----> Power +5V (white)
|
5 +---------+ 7
| x x o \
| o o o o |
4 +------------+ 1
| | | |
| | | +-> Ground (brown)
| | +----> Pulse (red)
| +-------> Latch (orange)
+----------> Data (yellow)
*/
#define BIT(x) (0x01 << (x))
const int LED = 13;
const int PULSE = 8; // red
const int LATCH = 10; // orange
const int DATA = 7; // yellow
void setup() {
pinMode(LED, OUTPUT);
pinMode(PULSE, OUTPUT);
pinMode(LATCH, OUTPUT);
pinMode(DATA, INPUT);
digitalWrite(LATCH, 0);
digitalWrite(PULSE, 1);
digitalWrite(DATA, 1); // data is up by default, goes to ground if key is pressed
}
#define BUTTON_A (0)
#define BUTTON_B (1)
#define BUTTON_SELECT (2)
#define BUTTON_START (3)
#define BUTTON_UP (4)
#define BUTTON_DOWN (5)
#define BUTTON_LEFT (6)
#define BUTTON_RIGHT (7)
char buttons[8];
void loop() {
delayMicroseconds(16*1000);
cli();
digitalWrite(LATCH, 1);
delayMicroseconds(12);
digitalWrite(LATCH, 0);
buttons[BUTTON_A] = 1 - digitalRead(DATA); // DATA goes to ground if button pressed
delayMicroseconds(6);
for (int i=1;i<8;++i) {
digitalWrite(PULSE, 1);
delayMicroseconds(6);
buttons[i] = 1 - digitalRead(DATA);
digitalWrite(PULSE, 0);
delayMicroseconds(5);
}
sei();
// Light up the LED if any key was pressed.
int blink = 0;
for (int i=0;i<8;++i) {
blink = blink || buttons[i];
}
digitalWrite(LED, blink);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment