Sunday, July 24, 2022

RP2040 Micropython PIO - Part 2 - Reading all the pins!

 The next thing I wanted to get working with PIO was reading the pin values.   I struggled with this until I realized that I needed to initialize the pins and set them to pull_up before starting the state machine.  Anyway, here's an example reading all available pins and returning their states on the fifo:

@rp2.asm_pio( set_init=[PIO.IN_HIGH]*32 )
def echo_pins():
wrap_target()
in_(pins, 32)
push()

set(x, 31) # call nop 32 times to slow things down
label("aloop")
nop() [31]
jmp(x_dec, "aloop")

wrap()

for n in range(32): # Initialize all the pins with PULL_UP
try:
Pin(n, Pin.IN, Pin.PULL_UP)
except:
print("Couldn't initialize pin:", n)

sm = rp2.StateMachine(0, pio_junk.echo_pins,
freq=2000,
in_base=Pin(0))

sm.active(1)
for n in range(10): # pull pin states from the fifo ten times!
out = sm.get()
print(f'{n}, {out:>032b}')
sm.active(0)

And the output looks like the following.  Some of the bits change as I press keys on the keyboard:

>>>
MPY: soft reboot
Checking Safety Pin 25...
In Main Now
Couldn't initialize pin: 30
Couldn't initialize pin: 31
0, 00111110111111111111101111111011
1, 00111110111111111111101111111011
2, 00111110111111111111101111111011
3, 00111110111111111111101111111011
4, 00111110110101011111101101111011
5, 00111110110101011111101101111011
6, 00111110110101011111101101111011
7, 00111110111111111111101111111011
8, 00111110111111111111101111111011
9, 00111110110101011111101101111011
MicroPython v1.19.1 on 2022-06-18; Arduino Nano RP2040 Connect with RP2040
Type "help()" for more information.
>>>

In Part 3, we'll track the pin states and  only output a value when there is a change.  

And in Part 4, we'll use an irq to trigger a python function only when there is a key press event so we don't need to keep a cpu core busy watching for button presses. 

No comments: