from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
import time
from time import sleep
# Define stepper motor pins and control pins
stepper_pins = [Pin(18, Pin.OUT), Pin(19, Pin.OUT), Pin(20, Pin.OUT), Pin(21, Pin.OUT)]
sw_pin = Pin(1, Pin.IN) # Switch pin
led_pin = Pin(2, Pin.OUT) # LED pin
@asm_pio(set_init=(PIO.OUT_LOW,)*4)
def stepper():
label("start")
set(pins, 8) # Step 1 (CW)
set(x, 31) # Delay for 31 cycles (for step rate of 10 Hz)
label("delay1")
nop() # No operation for delay
jmp(x_dec, "delay1") # Decrease x and repeat until zero
set(pins, 4) # Step 2 (CW)
set(x, 31)
label("delay2")
nop()
jmp(x_dec, "delay2")
set(pins, 2) # Step 3 (CW)
set(x, 31)
label("delay3")
nop()
jmp(x_dec, "delay3")
set(pins, 1) # Step 4 (CW)
set(x, 31)
label("delay4")
nop()
jmp(x_dec, "delay4")
jmp("start") # Repeat the process to rotate clockwise
# Initialize the state machine for the stepper motor with a 10 Hz step rate
sm = StateMachine(0, stepper, freq=2000, set_base=stepper_pins[0])
# Main loop
while True:
if sw_pin.value() == 0: # If switch is pressed (active low)
led_pin.toggle() # Turn LED on
sm.active(1) # Start stepper motor
else:
led_pin.toggle() # Blink LED at 2 Hz (500 ms ON and OFF)
sm.active(0) # Stop stepper motor
sleep(0.5) # Blink delay (500 ms)