···
-
# Define pins for stepper motors
-
motor1_step = digitalio.DigitalInOut(board.GP11)
-
motor1_step.direction = digitalio.Direction.OUTPUT
-
motor1_dir = digitalio.DigitalInOut(board.GP10)
-
motor1_dir.direction = digitalio.Direction.OUTPUT
-
motor2_step = digitalio.DigitalInOut(board.GP8)
-
motor2_step.direction = digitalio.Direction.OUTPUT
-
motor2_dir = digitalio.DigitalInOut(board.GP7)
-
motor2_dir.direction = digitalio.Direction.OUTPUT
-
enable = digitalio.DigitalInOut(board.GP9)
-
enable.direction = digitalio.Direction.OUTPUT
-
last_serial_check = time.monotonic()
-
SERIAL_CHECK_INTERVAL = 0.1 # Check serial every 1ms
-
print("Motors enabled")
-
STEPS_PER_REVOLUTION = 200 # For a typical 1.8° stepper motor
-
self.direction = True # True for forward
-
self.last_step_time = 0
-
def calculate_step_delay(speed):
-
return 1 / (STEPS_PER_REVOLUTION * speed)
-
def handle_command(command):
-
parts = command.split()
-
speed = 1 # Default speed
-
speed = float(parts[1])
-
print("Invalid speed value")
-
if command == "forward1":
-
motor1.direction = True
-
motor1_dir.value = True
-
print(f"Moving motor 1 forward at {speed} rotations per second...")
-
elif command == "forward2":
-
motor2.direction = True
-
motor2_dir.value = True
-
print(f"Moving motor 2 forward at {speed} rotations per second...")
-
elif command == "reverse1":
-
motor1.direction = False
-
motor1_dir.value = False
-
print(f"Moving motor 1 in reverse at {speed} rotations per second...")
-
elif command == "reverse2":
-
motor2.direction = False
-
motor2_dir.value = False
-
print(f"Moving motor 2 in reverse at {speed} rotations per second...")
-
elif command == "stop1":
-
print("Motor 1 stopped")
-
elif command == "stop2":
-
print("Motor 2 stopped")
-
elif command == "stop":
-
print("All motors stopped")
-
print("Unknown command. Use 'forward1/2 [speed]', 'reverse1/2 [speed]' or 'stop1/2'")
-
def step_motor(motor_state, step_pin):
-
if not motor_state.running:
-
current_time = time.monotonic()
-
step_delay = calculate_step_delay(motor_state.speed)
-
if (current_time - motor_state.last_step_time) >= step_delay:
-
step_pin.value = not step_pin.value # Toggle the pin
-
motor_state.last_step_time = current_time
-
current_time = time.monotonic()
-
# Check serial input less frequently
-
if current_time - last_serial_check >= SERIAL_CHECK_INTERVAL:
-
if supervisor.runtime.serial_bytes_available:
-
byte = sys.stdin.read(1)
-
if byte in ('\x08', '\x7f'):
-
command_buffer = command_buffer[:-1]
-
print('\x08 \x08', end='')
-
elif byte == '\n' or byte == '\r':
-
handle_command(command_buffer.strip().lower())
-
last_serial_check = current_time
-
# Handle motor stepping
-
step_motor(motor1, motor1_step)
-
step_motor(motor2, motor2_step)