from machine import Pin
from time import sleep
# Wait for USB to become ready
sleep(0.1)
print("Practice 2: Multi-Smart Toggle Started")
# --- Configuration ---
# Define pairs of GPIO pins: [LED_Pin, Button_Pin]
# You can add as many pairs here as you like!
config_pairs = [
[15, 16], # Pair 1 (Original)
[14, 17], # Pair 2
[13, 18] # Pair 3
]
# --- Setup Lists ---
led_objects = []
button_objects = []
led_states = []
prev_button_states = []
# Initialize all pins using a loop
for pair in config_pairs:
# Setup LED
led = Pin(pair[0], Pin.OUT)
led_objects.append(led)
led_states.append(0) # Start OFF
# Setup Button
btn = Pin(pair[1], Pin.IN, Pin.PULL_DOWN)
button_objects.append(btn)
prev_button_states.append(0) # Track previous state for edge detection
print(f"System ready with {len(config_pairs)} switch pairs.")
# --- Main Loop ---
while True:
# Loop through every pair defined in our configuration
for i in range(len(config_pairs)):
current_btn_val = button_objects[i].value()
# Check for "Rising Edge" (Button went from 0 to 1)
# This replaces the blocking 'while' loop
if current_btn_val == 1 and prev_button_states[i] == 0:
# Toggle the state
led_states[i] = not led_states[i]
# Update the hardware
led_objects[i].value(led_states[i])
print(f"Pair {i+1} (LED GP{config_pairs[i][0]}) toggled to {int(led_states[i])}")
# Update the previous state tracker for the next loop iteration
prev_button_states[i] = current_btn_val
# Small delay to prevent CPU overload and handle minor bouncing
sleep(0.05)