# Import necessary modules from MicroPython's machine library
from machine import Pin, ADC  
import time  # Import time module to add delays

# Set up the X-axis joystick input
# ADC (Analog-to-Digital Converter) reads an analog voltage (0V - 3.3V) 
# and converts it to a digital value (0 - 4095 on ESP32)
x_axis = ADC(Pin(34))  # Connect joystick X output to GPIO 34

# Set up the Y-axis joystick input (same as X but for vertical movement)
y_axis = ADC(Pin(35))  # Connect joystick Y output to GPIO 35

# Set up the joystick button as a digital input
# PULL_UP means the button defaults to "1" (HIGH) when not pressed
# When pressed, it connects to ground (0 or LOW)
button = Pin(13, Pin.IN, Pin.PULL_UP)  # Connect joystick button to GPIO 13

# Infinite loop to continuously read joystick and button values
while True:
    x = x_axis.read()  # Read the X-axis analog value (0 - 4095)
    y = y_axis.read()  # Read the Y-axis analog value (0 - 4095)
    btn = button.value()  # Read button state (1 = not pressed, 0 = pressed)

    # Print the values to the console
    # This helps visualize joystick movements and button presses
    print(f"X: {x}, Y: {y}, Button: {btn}")

    if x > 2048:
      print("Left!")
    elif x < 2048:
      print("Right!")

    if y > 2048:
      print("Up!")
    elif y < 2048:
      print("Down!")

    if x == 2048 and y == 2048:
      print("Controler is neutral")
   

    # Small delay (100ms) to slow down loop execution
    # Without this, the ESP32 would flood the console with too many messages
    time.sleep(01)  
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK
joystick1:VCC
joystick1:VERT
joystick1:HORZ
joystick1:SEL
joystick1:GND