from machine import Pin
import rp2
import time
# Set up the button on pin 1
button = Pin(1, Pin.IN, Pin.PULL_UP)
# Define PIO program for controlling stepper motor (Clockwise)
@rp2.asm_pio(set_init=(rp2.PIO.OUT_LOW,)*4)
def stepper_clockwise():
label("start")
# Step 1: Pin 21 (A-negative) = High, others = Low
set(pins, 2)
set(x, 5) # Delay loop (5 * 32 cycles = 160 cycles)
label("delay1")
nop() [31] # Delay loop
jmp(x_dec, "delay1")
# Step 2: Pin 20 (A-positive) = High, others = Low
set(pins, 8)
set(x, 5) # Delay loop (5 * 32 cycles = 160 cycles)
label("delay2")
nop() [31] # Delay loop
jmp(x_dec, "delay2")
# Step 3: Pin 19 (B-positive) = High, others = Low
set(pins, 1)
set(x, 5) # Delay loop (5 * 32 cycles = 160 cycles)
label("delay3")
nop() [31] # Delay loop
jmp(x_dec, "delay3")
# Step 4: Pin 18 (B-negative) = High, others = Low
set(pins, 4)
set(x, 5) # Delay loop (5 * 32 cycles = 160 cycles)
label("delay4")
nop() [31] # Delay loop
jmp(x_dec, "delay4")
# Define PIO program for controlling stepper motor (Counterclockwise)
@rp2.asm_pio(set_init=(rp2.PIO.OUT_LOW,)*4)
def stepper_counterclockwise():
label("start")
# Step 1: Pin 21 (A-negative) = High, others = Low
set(pins, 4)
set(x, 5) # Delay loop (5 * 32 cycles = 160 cycles)
label("delay1")
nop() [31] # Delay loop
jmp(x_dec, "delay1")
# Step 2: Pin 20 (A-positive) = High, others = Low
set(pins, 1)
set(x, 5) # Delay loop (5 * 32 cycles = 160 cycles)
label("delay2")
nop() [31] # Delay loop
jmp(x_dec, "delay2")
# Step 3: Pin 19 (B-positive) = High, others = Low
set(pins, 8)
set(x, 5) # Delay loop (5 * 32 cycles = 160 cycles)
label("delay3")
nop() [31] # Delay loop
jmp(x_dec, "delay3")
# Step 4: Pin 18 (B-negative) = High, others = Low
set(pins, 2)
set(x, 5) # Delay loop (5 * 32 cycles = 160 cycles)
label("delay4")
nop() [31] # Delay loop
jmp(x_dec, "delay4")
# Create the state machine for controlling stepper motor
def activate_stepper(sm_program):
sm = rp2.StateMachine(0, sm_program, freq=2000, set_base=Pin(18)) # Pins 18-21 for stepper motor
sm.active(1)
return sm
# Initialize the state machine for stepper (default to clockwise)
sm = activate_stepper(stepper_clockwise)
current_direction = 'clockwise' # Default direction
# Main loop to check button and activate stepper motor direction
while True:
if button.value() == 0: # Button pressed
if current_direction != 'counterclockwise':
print("Counterclockwise")
sm.active(0) # Deactivate the current state machine
sm = activate_stepper(stepper_counterclockwise) # Activate counterclockwise
current_direction = 'counterclockwise'
else: # Button not pressed
if current_direction != 'clockwise':
print("Clockwise")
sm.active(0) # Deactivate the current state machine
sm = activate_stepper(stepper_clockwise) # Activate clockwise
current_direction = 'clockwise'
time.sleep(0.1) # Debounce delay