from machine import Pin
from time import sleep
# Define pins for stepper motor control
step_pin = Pin(19, Pin.OUT)
dir_pin = Pin(18, Pin.OUT)
angle_increment = 1.8 # Angle per step in full-step mode
motor_position = 0 # Tracks the current angle of the motor
def step():
"""Triggers a single step for the stepper motor."""
step_pin.on()
sleep(0.05)
step_pin.off()
sleep(0.05)
def change_dir(direction):
"""Changes the direction of the motor."""
global angle_increment
dir_pin.value(direction)
angle_increment = abs(angle_increment) if direction == 1 else -abs(angle_increment)
def move_steps(num_steps):
"""Moves the motor a specific number of steps."""
global motor_position
direction = 1 if num_steps > 0 else 0
change_dir(direction)
for _ in range(abs(num_steps)):
step()
motor_position += angle_increment
print(f'Current Angle: {motor_position:.2f}°')
def move_to_angle(new_position):
"""Moves the motor to a specific absolute angle."""
global motor_position
angle_to_move = new_position - motor_position
steps_to_move = round(angle_to_move / angle_increment)
move_steps(steps_to_move)
# Interactive Serial Input
print("Stepper Motor Control")
print("Enter 's' followed by a number to move steps (e.g., s 100)")
print("Enter 'a' followed by an angle to move to (e.g., a 90)")
while True:
user_input = input("Command: ").lower()
if user_input.startswith("s"):
steps = int(user_input.split()[1])
move_steps(steps)
elif user_input.startswith("a"):
angle = float(user_input.split()[1])
move_to_angle(angle)
else:
print("Invalid command. Use 's <steps>' or 'a <angle>'.")