3 * Driver for the NES Joystick controller on the Raspberry Pi
4 * Copyright (c) 2012 Gordon Henderson
5 ***********************************************************************
6 * This file is part of wiringPi:
7 * https://projects.drogon.net/raspberry-pi/wiringpi/
9 * wiringPi is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Lesser General Public License as
11 * published by the Free Software Foundation, either version 3 of the
12 * License, or (at your option) any later version.
14 * wiringPi is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with wiringPi.
21 * If not, see <http://www.gnu.org/licenses/>.
22 ***********************************************************************
29 #define MAX_NES_JOYSTICKS 8
31 #define NES_RIGHT 0x01
35 #define NES_START 0x10
36 #define NES_SELECT 0x20
41 // Data to store the pins for each controller
45 unsigned int cPin, dPin, lPin ;
48 static struct nesPinsStruct nesPins [MAX_NES_JOYSTICKS] ;
50 static int joysticks = 0 ;
55 * Create a new NES joystick interface, program the pins, etc.
56 *********************************************************************************
59 int setupNesJoystick (int dPin, int cPin, int lPin)
61 if (joysticks == MAX_NES_JOYSTICKS)
64 nesPins [joysticks].dPin = dPin ;
65 nesPins [joysticks].cPin = cPin ;
66 nesPins [joysticks].lPin = lPin ;
68 digitalWrite (lPin, LOW) ;
69 digitalWrite (cPin, LOW) ;
71 pinMode (lPin, OUTPUT) ;
72 pinMode (cPin, OUTPUT) ;
73 pinMode (dPin, INPUT) ;
81 * Do a single scan of the NES Joystick.
82 *********************************************************************************
85 unsigned int readNesJoystick (int joystick)
87 unsigned int value = 0 ;
90 struct nesPinsStruct *pins = &nesPins [joystick] ;
92 // Toggle Latch - which presents the first bit
94 digitalWrite (pins->lPin, HIGH) ;
95 delayMicroseconds (1) ;
96 digitalWrite (pins->lPin, LOW) ;
97 delayMicroseconds (1) ;
101 value = digitalRead (pins->dPin) ;
103 // Now get the next 7 bits with the clock
105 for (i = 0 ; i < 7 ; ++i)
107 digitalWrite (pins->cPin, HIGH) ;
108 delayMicroseconds (1) ;
109 digitalWrite (pins->cPin, LOW) ;
110 delayMicroseconds (1) ;
111 value = (value << 1) | digitalRead (pins->dPin) ;