##############################################################
# Joystick Interface #
##############################################################
#
# Interface Joystick with Raspberry Pi Pico using MicroPython (Hardware & Simulation)
#
# Check out the link for Code explanation and Hardware details
# Link:
# http://tech.arunkumarn.in/blogs/raspberry-pi-pico/how-to-connect-a-joystick-to-raspberry-pi-pico-using-micropython/
#
#
from machine import Pin, ADC
from time import sleep
# Initialize ADC channels for X and Y axes
adc_x = ADC(Pin(26)) # GP26 -> ADC0
adc_y = ADC(Pin(27)) # GP27 -> ADC1
# Initialize button pin with internal pull-up
button = Pin(28, Pin.IN, Pin.PULL_UP)
# ADC reading: returns 16-bit scaled value (0-65535)
def read_adc(adc):
return adc.read_u16()
# Debounced button read
def read_button():
return not button.value() # Active-low: pressed = False ā return True
try:
print("š® Joystick Ready! Press Ctrl+C to exit.")
while True:
# Read ADC values (16-bit scaled: 0-65535)
x_raw = read_adc(adc_x)
y_raw = read_adc(adc_y)
# Optional: Map to -100 to +100 range for intuitive control
x_norm = int((x_raw - 32768) * 100 // 32768)
y_norm = int((y_raw - 32768) * 100 // 32768)
# Read button state
btn_pressed = read_button()
# Output to console
print(f"X: {x_raw:5d} ({x_norm:+4d}) | "
f"Y: {y_raw:5d} ({y_norm:+4d}) | "
f"Button: {'PRESSED' if btn_pressed else 'RELEASED'}",
end='\r')
sleep(0.1) # Small delay for stable reading
except KeyboardInterrupt:
print("\n\nš Joystick interface stopped.")