############################
# E057_JOYSTICK.PY: Lee valores X, y, SW de un joystick
# ENTRADAS: Posición del joystick
# SALIDAS: Valores X, Y, SW en plotter
############################
from machine import Pin, ADC # Gestión GPIO y ADC
import utime # Control de tiempos
# Configuración de pines
pin_x = Pin(32, Pin.IN) # Posición X
pin_y = Pin(35, Pin.IN) # Posición Y
pin_s = Pin(14, Pin.IN) # Pulsador on/off
# Posición inicial del joystick
x_init = y_init = 2048
s_init = 0
# Lee el valor analógico del joystick
def leer_joystick(pin):
adc = ADC(pin) # Activa ADC en pin
adc.atten(ADC.ATTN_11DB) # Rango 0-3.3V (defecto 0-1V)
return adc.read() # Devuelve la lectura del ADC
# Bucle principal del script
print('CONTROL DE UN JOYSTICK')
print('Mueve y/o presiona el mando...')
try:
while True:
valor_x = 4095- leer_joystick(pin_x) # Posición en X
valor_y = leer_joystick(pin_y) # Posición en Y
valor_s = pin_s.value() # Pulsación del mando
# Visualiza valores de X, Y, S si cambian
if valor_x != x_init or valor_y != y_init or valor_s != s_init:
print("X:", valor_x, "Y:", valor_y, "Switch:", valor_s)
x_init = valor_x
y_init = valor_y
s_init = valor_s
utime.sleep_ms(100) # Espera entre lecturas
except KeyboardInterrupt:
print('Programa finalizado...')