Use a joystick with your raspberry pi pico!

At some point, you may want to connect a joystick to your pi pico to read position. One option is Digilent’s PMod Joystick 2, which communicates through SPI. Fortunately, it is very easy to set up SPI communication on the rasperry pi pico!

import machine
import utime
import ustruct
import sys
from machine import Pin
#PMOD2 Joystick
#4 pins
led_up = Pin(13, Pin.OUT)
led_down = Pin(15, Pin.OUT)
led_right = Pin(12, Pin.OUT)
led_left = Pin(14, Pin.OUT)
led_up.value(0)
led_right.value(0)
led_down.value(0)
led_left.value(0)
cs = machine.Pin(17, machine.Pin.OUT)
spi = machine.SPI(0,
baudrate= 10000,
bits = 8,
firstbit=machine.SPI.MSB,
sck=machine.Pin(18),
mosi=machine.Pin(19),
miso=machine.Pin(16))
def getPosition(spi, cs):
msg = bytearray()
msg.append(0xC0)
msg.append(0x00)
msg.append(0x00)
msg.append(0x00)
msg.append(0x00)
cs.value(0)
spi.write(msg)
cs.value(1)
utime.sleep_us(25)
cs.value(0)
spi.write(msg)
data = spi.read(5)
cs.value(1)
return data
while 1:
data = getPosition(spi, cs)
print (data)
print (data[0])
print (data[1])
if data[0] > 225:
print ('RIGHT')
led_right.value(1)
else:
led_right.value(0)
if data[0] < 50:
print ('LEFT')
led_left.value(1)
else:
led_left.value(0)
if data[1] > 225:
print ('DOWN')
led_down.value(1)
else:
led_down.value(0)
if data[1] < 55:
print ('UP')
led_up.value(1)
else:
led_up.value(0)
utime.sleep(0.05)