Untitled
from machine import Pin, ADC import time # Define LED pins led_pins = [Pin(i, Pin.OUT) for i in range(1, 11)] # Initialize joystick and button joystick_x = ADC(27) joystick_button = Pin(28, Pin.IN, Pin.PULL_UP) # Initial states bargraph_enabled = True last_button_state = 1 current_position = 0 joystick_moved = False # Threshold values for joystick movement LEFT_THRESHOLD = 20000 RIGHT_THRESHOLD = 45000 NEUTRAL_THRESHOLD_LOW = 30000 NEUTRAL_THRESHOLD_HIGH = 35000 def turn_off_all_leds(): """Turns off all LEDs.""" for led in led_pins: led.value(0) def update_leds(position): """Updates LED states based on joystick position.""" for i, led in enumerate(led_pins): led.value(1 if i == position else 0) def read_joystick(): """Reads joystick position and updates the LED bar graph accordingly.""" global joystick_moved, current_position x_value = joystick_x.read_u16() if x_value < LEFT_THRESHOLD and not joystick_moved and current_position > 0: current_position -= 1 joystick_moved = True print(f"Joystick moved left to position {current_position}") elif x_value > RIGHT_THRESHOLD and not joystick_moved and current_position < len(led_pins) - 1: current_position += 1 joystick_moved = True print(f"Joystick moved right to position {current_position}") elif NEUTRAL_THRESHOLD_LOW <= x_value <= NEUTRAL_THRESHOLD_HIGH: joystick_moved = False # Reset joystick movement flag when in neutral while True: # Handle button press for enabling/disabling LED bargraph button_state = joystick_button.value() if button_state == 0 and last_button_state == 1: bargraph_enabled = not bargraph_enabled print(f"Bargraph {'enabled' if bargraph_enabled else 'disabled'}") time.sleep(0.1) # Debounce delay last_button_state = button_state if bargraph_enabled: read_joystick() update_leds(current_position) else: turn_off_all_leds() time.sleep(0.05) # Main loop delay
Leave a Comment