from machine import Pin, ADC, Timer
class Joystick:
def __init__(self, xAxis: int, yAxis: int, buttonPin: int, mode: str):
# Write your code here
self.x_axis = ADC(Pin(xAxis))
self.y_axis = ADC(Pin(yAxis))
self.button = Pin(buttonPin, Pin.IN, Pin.PULL_UP)
self.mode = mode
self.x = 0
self.y = 0
self.button_state = 1
if(self.mode == "interrupt"):
self.interval = 100
self.timer = Timer(0)
self.timer.init(period=self.interval, mode=Timer.PERIODIC, callback=self.read_interupt)
def read_interupt(self, timer):
self.x = self.x_axis.read() # Read the X-axis analog value (0 - 4095)
self.y = self.y_axis.read() # Read the Y-axis analog value (0 - 4095)
self.button_state = self.button.value() # Read button state (1 = not pressed, 0 = pressed)
# This function reads the joystick and returns the joystick state:
# L: left R: Right U: Up D: Down M: Middle
def read(self):
# Write your code here
if(self.mode != "interrupt"):
self.x = self.x_axis.read() # Read the X-axis analog value (0 - 4095)
self.y = self.y_axis.read() # Read the Y-axis analog value (0 - 4095)
self.button_state = self.button.value() # Read button state (1 = not pressed, 0 = pressed)
else:
print("Mode is interrupt, reading is done in a timer callback")
# Determine joystick direction based on x and y values
if self.x > 2048:
direction = 'L' # Left
elif self.x < 2048:
direction = 'R' # Right
elif self.y < 2048:
direction = 'D' # Down
elif self.y > 2048:
direction = 'U' # Up
else:
direction = 'M' # Middle
return direction, self.button_state # Return direction and button state