pimoroni-pico/micropython/examples/motor2040/motor_cluster.py

65 lines
1.7 KiB
Python
Raw Normal View History

2022-04-07 17:57:38 +01:00
import gc
import time
import math
2022-04-20 18:55:39 +01:00
from motor import MotorCluster, motor2040
2022-04-07 17:57:38 +01:00
"""
2022-04-20 18:55:39 +01:00
Demonstrates how to create a MotorCluster object to control multiple motors at once.
2022-04-07 17:57:38 +01:00
2022-04-20 18:55:39 +01:00
NOTE: MotorCluster uses the RP2040's PIO system, and as
2022-04-07 17:57:38 +01:00
such may have problems when running code multiple times.
If you encounter issues, try resetting your board.
"""
2022-04-20 18:55:39 +01:00
# Free up hardware resources ahead of creating a new MotorCluster
2022-04-07 17:57:38 +01:00
gc.collect()
2022-04-20 18:55:39 +01:00
# Create a motor cluster, using PIO 0 and State Machine 0
MOTOR_PINS = [motor2040.MOTOR_A, motor2040.MOTOR_B, motor2040.MOTOR_C, motor2040.MOTOR_D]
motors = MotorCluster(pio=0, sm=0, pins=MOTOR_PINS)
2022-04-07 17:57:38 +01:00
2022-04-20 18:55:39 +01:00
# Enable all motors
motors.enable_all()
2022-04-07 17:57:38 +01:00
time.sleep(2)
2022-04-20 18:55:39 +01:00
# Drive at full positive
motors.all_full_positive()
2022-04-07 17:57:38 +01:00
time.sleep(2)
2022-04-20 18:55:39 +01:00
# Stop all moving
motors.stop_all()
2022-04-07 17:57:38 +01:00
time.sleep(2)
2022-04-20 18:55:39 +01:00
# Drive at full negative
motors.all_full_negative()
2022-04-07 17:57:38 +01:00
time.sleep(2)
2022-04-20 18:55:39 +01:00
# Coast all to a gradual stop
motors.coast_all()
time.sleep(2)
SWEEPS = 2 # How many sweeps of the motors to perform
2022-04-07 17:57:38 +01:00
STEPS = 10 # The number of discrete sweep steps
STEPS_INTERVAL = 0.5 # The time in seconds between each step of the sequence
2022-04-20 18:55:39 +01:00
SPEED_EXTENT = 1.0 # How far from zero to drive the motors when sweeping
2022-04-07 17:57:38 +01:00
2022-04-20 18:55:39 +01:00
# Do a sine speed sweep
2022-04-07 17:57:38 +01:00
for j in range(SWEEPS):
for i in range(360):
2022-04-20 18:55:39 +01:00
speed = math.sin(math.radians(i)) * SPEED_EXTENT
motors.all_to_speed(speed)
2022-04-07 17:57:38 +01:00
time.sleep(0.02)
2022-04-20 18:55:39 +01:00
# Do a stepped speed sweep
2022-04-07 17:57:38 +01:00
for j in range(SWEEPS):
for i in range(0, STEPS):
2022-04-20 18:55:39 +01:00
motors.all_to_percent(i, 0, STEPS, 0.0 - SPEED_EXTENT, SPEED_EXTENT)
2022-04-07 17:57:38 +01:00
time.sleep(STEPS_INTERVAL)
for i in range(0, STEPS):
2022-04-20 18:55:39 +01:00
motors.all_to_percent(i, STEPS, 0, 0.0 - SPEED_EXTENT, SPEED_EXTENT)
2022-04-07 17:57:38 +01:00
time.sleep(STEPS_INTERVAL)
2022-04-20 18:55:39 +01:00
# Disable the motors
motors.disable_all()