Created
August 9, 2021 14:27
-
-
Save flavioamieiro/54d616db4efe8f8a7bdd220efdd72315 to your computer and use it in GitHub Desktop.
Reading an NES controller using RP2040's PIO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import rp2 | |
from machine import Pin | |
from ucollections import OrderedDict | |
led_1 = Pin(25, Pin.OUT) | |
@rp2.asm_pio(set_init=(rp2.PIO.OUT_LOW, rp2.PIO.OUT_LOW), push_thresh=8, autopush=True) | |
def read_NES_buttons(): | |
wrap_target() | |
set(x, 7) | |
set(pins, 0b10) [1] | |
set(pins, 0b00) | |
label("btn_loop") | |
in_(pins, 1) | |
set(pins, 0b01) [1] | |
set(pins, 0b00) | |
jmp(x_dec, "btn_loop") | |
set(pins, 0b01) [1] | |
set(pins, 0b00) | |
wrap() | |
def get_buttons_from_state(state): | |
buttons = OrderedDict([ | |
("A", False), | |
("B", False), | |
("SELECT", False), | |
("START", False), | |
("UP", False), | |
("DOWN", False), | |
("LEFT", False), | |
("RIGHT", False), | |
]) | |
for i, button in enumerate(buttons.keys()): | |
buttons[button] = not bool(state & (1 << 7 - i)) | |
return buttons | |
state_machine = rp2.StateMachine( | |
0, read_NES_buttons, freq=2000, set_base=Pin(0), in_base=Pin(15) | |
) | |
state_machine.active(1) | |
while True: | |
buttons = get_buttons_from_state(state_machine.get()) | |
print(list(filter(lambda x: buttons[x], buttons.keys()))) | |
led_1.value(buttons["B"]) | |
time.sleep(0.01) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment