from machine import Pin, PWM, ADC
import time
# Configure the joystick's pins
vert = ADC(Pin(34)) # Vertical axis (VERT)
horz = ADC(Pin(35)) # Horizontal axis (HORZ)
sel = Pin(25, Pin.IN, Pin.PULL_UP) # Button (SEL)
# Configure ADC settings
vert.width(ADC.WIDTH_10BIT) # 10-bit resolution (0-1023)
horz.width(ADC.WIDTH_10BIT)
vert.atten(ADC.ATTN_11DB) # Measure voltage range 0-3.3V
horz.atten(ADC.ATTN_11DB)
# Configure the servo
servo = PWM(Pin(13), freq=50) # Servo control pin (GPIO13), 50Hz frequency
def set_servo_angle(angle):
"""Converts angle (0-180) to duty cycle for the servo."""
duty = int((angle / 180) * 102 + 26) # Convert angle to duty (26-128)
servo.duty(duty)
while True:
# Read the joystick horizontal axis (HORZ)
horizontal = horz.read() # Value for horizontal movement (0-1023)
# Map the joystick's horizontal value (0-1023) to an angle (0-180)
angle = int((horizontal / 1023) * 180) # Map to 0-180 degrees
set_servo_angle(angle) # Set the servo position based on the joystick input
# Optional: Check for button press and do something
button_state = sel.value()
if button_state == 0:
print("Button Pressed!") # Optional, replace with your custom behavior
time.sleep(0.1)