import time
from machine import Pin
time.sleep(0.1) # Wait for USB to become ready
print("Hello, Pi Pico!")
# Pin definitions
led_pin = Pin(2, Pin.OUT)
button_pin = Pin(1, Pin.IN, Pin.PULL_UP)
step_a_minus = Pin(21, Pin.OUT)
step_a_plus = Pin(20, Pin.OUT)
step_b_plus = Pin(19, Pin.OUT)
step_b_minus = Pin(18, Pin.OUT)
# Step sequence for the stepper motor
step_sequence = [
(1, 0, 1, 0), # A+ and B+
(0, 1, 1, 0), # A- and B+
(0, 1, 0, 1), # A- and B-
(1, 0, 0, 1), # A+ and B-
]
# Step index to track the current step in the sequence
current_step = 0
# Function to rotate the stepper motor by one step
def stepper_rotate_one_step(clockwise=True):
global current_step
# Determine the next step based on direction
if clockwise:
current_step = (current_step + 1) % 4
else:
current_step = (current_step - 1) % 4
# Apply the current step
step = step_sequence[current_step]
step_a_plus.value(step[0])
step_a_minus.value(step[1])
step_b_plus.value(step[2])
step_b_minus.value(step[3])
# Main loop
while True:
if button_pin.value() == 0: # Button pressed
print("Button pressed!")
led_pin.value(0) # Turn ON LED
# Rotate the motor continuously at 10 Hz while the button is pressed
start_time = time.ticks_ms()
while button_pin.value() == 0: # Stay in this loop while the button is pressed
stepper_rotate_one_step(clockwise=True) # Rotate one step clockwise
time.sleep(0.1) # Delay for 10 Hz step rate
# Prevent infinite loop from locking
if time.ticks_diff(time.ticks_ms(), start_time) > 10000: # Safety timeout
break
else: # Button not pressed
print("Button not pressed.")
led_pin.value(1) # Turn OFF LED
# Stop stepper motor
step_a_plus.value(0)
step_a_minus.value(0)
step_b_plus.value(0)
step_b_minus.value(0)