import time
from machine import Pin
import rp2
time.sleep(0.1) # Wait for USB to become ready
print("Hello, Pi Pico!")
# Pin definitions
led_pin = Pin(2, Pin.OUT)
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
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])
# PIO program to read data from UART TX FIFO (state machine)
@rp2.asm_pio(out_init=(rp2.PIO.OUT_LOW,))
def uart_rx():
pull() # Pull data from the RX FIFO into the state machine
mov(isr, x) # Move the received value into the ISR register
# Create a state machine and associate it with the PIO program
sm = rp2.StateMachine(0, uart_rx, freq=1000000) # Removed `in_pin` argument
# Function to check if the character 'A' was received
def detect_char():
try:
return sm.get() == ord('A') # Compare received data with ASCII 'A'
except IndexError:
return False # If no data is available in the RX FIFO
# Start the state machine
sm.active(1)
# Main loop
while True:
# If 'A' is received, rotate clockwise, else rotate counter-clockwise
if detect_char(): # Character 'A' received
print("Detected 'A'. Rotating clockwise.")
led_pin.value(0) # Turn ON LED (clockwise)
stepper_rotate_one_step(clockwise=True) # Rotate motor clockwise
else:
print("No 'A' detected. Rotating counter-clockwise.")
led_pin.value(1) # Turn OFF LED (counter-clockwise)
stepper_rotate_one_step(clockwise=False) # Rotate motor counter-clockwise
# Step rate is 10 Hz (0.1 seconds per step)
time.sleep(0.1) # Step delay for 10 Hz