The motor library is a reusable Python module, saved as motor.py, that turns high-level movement requests into timed control of the robot’s two DC motors. Import it wherever an application needs the robot to move rather than duplicating motor-control code. section 3.11
Its core movement function sets each motor’s throttle from a speed level, a per-motor adjustment value, and a direction factor. It waits for the requested duration, then sets both throttles to zero. Named commands are built from that function: forward, backward, right, left, spin_right, spin_left, and noop. section 3.11
Listing 3.8 motor.py: Simplifying the way functions are defined
#!/usr/bin/env python3
from adafruit_crickit import crickit
import time
import os
from functools import partial
DC_ADJUST_R = float(os.environ.get('ROBO_DC_ADJUST_R', '1'))
DC_ADJUST_L = float(os.environ.get('ROBO_DC_ADJUST_L', '1'))
ADJUST = dict(R=DC_ADJUST_R, L=DC_ADJUST_L)
MOTOR = dict(R=crickit.dc_motor_1, L=crickit.dc_motor_2)
THROTTLE_SPEED = {0: 0, 1: 0.5, 2: 0.7, 3: 0.9}
def set_throttle(name, speed, factor=1):
MOTOR[name].throttle = THROTTLE_SPEED[speed] * ADJUST[name] * factor
def movement(duration=0.2, speed=3, factor_r=1, factor_l=1):
set_throttle('R', speed, factor_r)
set_throttle('L', speed, factor_l)
time.sleep(duration)
set_throttle('R', 0)
set_throttle('L', 0)
forward = partial(movement)
backward = partial(movement, factor_r=-1, factor_l=-1)
right = partial(movement, factor_r=0.5)
left = partial(movement, factor_l=0.5)
spin_right = partial(movement, factor_r=-1, factor_l=1)
spin_left = partial(movement, factor_r=1, factor_l=-1)
noop = lambda: None
This complete module maps speed levels and motor adjustments to throttle values, then defines the reusable directional commands with functools.partial. section 3.11
Use movement commands with optional duration and speed arguments:
- Call forward() or backward() for straight movement; backward reverses both motors. section 3.11
- Call right() or left() to reduce one motor’s speed and turn. section 3.11
- Call spin_right() or spin_left() to drive the motors in opposite directions. section 3.11
- Call noop() when a successful operation that performs no movement is useful, including performance testing. section 3.11
Web buttons for movement
A web handler can import motor and dispatch POST requests to motor.forward() and motor.backward(). The browser buttons provide the user interface; the motor library provides the physical action. With the default movement duration of 200 ms, logged movement requests take about 224 ms. section 6.3.3
QR-guided snack pushing
A QR-guided robot can select motor.forward or motor.backward dynamically with getattr, move in short repeated steps while checking QR codes, then back up before a servo arm pushes a matching snack. The movement library stays focused on driving while the project adds sensing and servo behavior. section 11.3.2
