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

66 lines
1.6 KiB
Python
Raw Normal View History

2022-04-07 17:57:38 +01:00
import time
import math
from motor import Motor, motor2040
"""
Demonstrates how to create multiple Motor objects and control them together.
"""
# Create a list of motors
2022-04-20 18:55:39 +01:00
MOTOR_PINS = [motor2040.MOTOR_A, motor2040.MOTOR_B, motor2040.MOTOR_C, motor2040.MOTOR_D]
2022-04-07 17:57:38 +01:00
motors = [Motor(pins) for pins in MOTOR_PINS]
2022-04-20 18:55:39 +01:00
# Enable all motors
2022-04-07 17:57:38 +01:00
for m in motors:
m.enable()
time.sleep(2)
2022-04-20 18:55:39 +01:00
# Drive at full positive
2022-04-07 17:57:38 +01:00
for m in motors:
m.full_positive()
time.sleep(2)
2022-04-20 18:55:39 +01:00
# Stop moving
for m in motors:
m.stop()
time.sleep(2)
# Drive at full negative
2022-04-07 17:57:38 +01:00
for m in motors:
m.full_negative()
time.sleep(2)
2022-04-20 18:55:39 +01:00
# Coast to a gradual stop
2022-04-07 17:57:38 +01:00
for m in motors:
2022-04-20 18:55:39 +01:00
m.coast()
2022-04-07 17:57:38 +01:00
time.sleep(2)
2022-04-20 18:55:39 +01:00
SWEEPS = 2 # How many speed 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):
speed = math.sin(math.radians(i)) * SPEED_EXTENT
for m in motors:
m.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):
for m in motors:
m.to_percent(i, 0, STEPS, 0.0 - SPEED_EXTENT, SPEED_EXTENT)
time.sleep(STEPS_INTERVAL)
for i in range(0, STEPS):
for m in motors:
m.to_percent(i, STEPS, 0, 0.0 - SPEED_EXTENT, SPEED_EXTENT)
time.sleep(STEPS_INTERVAL)
# Disable the motors
for m in motors:
m.disable()