This notebook assumes you’ve completed Lab2 Part 1 - Single Motor Control.ipynb and Lab2 Part 2 - Two Motor Control.ipynb. It contains three open-ended problems that build on the helper functions and hardware setup from those notebooks.
| Problem | Motors needed |
|---|---|
| Problem 1 — Step Response Through Five Angles | 1 motor |
| Problem 2 — Differential Drive: Forward and Turn | 2 motors, re-IDed and daisy-chained (from Part 2) |
| Problem 3 — Three Motors: Target Angles and Sine Wave Tracking | ⚠️ 3 motors — you’ll re-ID and daisy-chain a third motor as part of this problem |
# ── Session setup — run this cell at the start of every session ──────────────
import time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from Lab2_helpers import *
# ── Update these values to match your setup ─────────────────────────────────
PORT = "COM4" # from lerobot-find-port in Task 1 (see Lab2 Part 1)
MOTOR_ID = 1 # single motor (Problem 1)
MOTOR_ID_1 = 1 # first motor (Problems 2–3)
MOTOR_ID_2 = 2 # second motor (Problems 2–3; re-IDed in Lab2 Part 2, Task 3.1)
print("Lab 2 Problems ready.")
Problem 1 — Step Response Through Five Angles¶
Goal: Command the motor to move through the sequence of angles 0° → 45° → 90° → 135° → 180°, record the position response for each move, and plot all five curves on the same axes. From your plot, estimate how long the motor takes to settle at each target.
Background: Each time you send a new position command, the motor executes an internal trapezoidal velocity profile — it accelerates, cruises at peak speed, then decelerates into the target. A larger angular step requires a longer cruise phase, so it takes more time to arrive. This experiment lets you observe and measure that directly.
Steps:
Define the list of target angles:
[0, 45, 90, 135, 180]Connect the motor and send it to 0° first so all moves start from a known position
Loop through each target angle, calling
move_to_angle_and_record()to send the command and capture the 3-second responseDisconnect the motor
Plot all five step responses on the same axes; each curve starts near the previous angle and travels to the current one
What to fill in:
The call to
move_to_angle_and_record(...)inside the loopThe plotting loop (one
ax.plotcall per target)
Discussion question: Does a larger angular step (e.g., 0° → 90°) take more time to settle than a smaller one (e.g., 90° → 135°)? Why or why not?
import time
import numpy as np
# PORT and MOTOR_ID were set in the session setup cell above
# ── Parameters ────────────────────────────────────────────────────────────────
TARGET_ANGLES = [0, 45, 90, 135, 180] # sequence of target angles (degrees)
RECORD_SEC = 3.0 # seconds to record after each command
# We will store one (times, positions) pair per step
all_times = []
all_positions = []
# ── Connect the motor ─────────────────────────────────────────────────────────
bus = connect_motors(PORT, MOTOR_ID)
# Go to 0° first and wait for it to settle before starting the sequence
write_angles(bus, 0.0)
time.sleep(2.0)
print("Starting step sequence...")
# ── Loop through each target angle ────────────────────────────────────────────
for target in TARGET_ANGLES:
print(f" → Moving to {target}°")
# ── YOUR CODE HERE ─────────────────────────────────────────────────────────
# Call move_to_angle_and_record() to move the motor to `target` and record
# the position for RECORD_SEC seconds.
# Store the returned time and position arrays in variables t and pos.
#
# Hint: t, pos = move_to_angle_and_record(bus, target, record_sec=RECORD_SEC)
#
t, pos = None, None # replace this line with the correct function call
all_times.append(t)
all_positions.append(pos)
# ── Disconnect ────────────────────────────────────────────────────────────────
disconnect_motors(bus)
print("Done. Run the next cell to plot the results.")import matplotlib.pyplot as plt
colors = ["#2c3e50", "#e74c3c", "#e67e22", "#27ae60", "#2980b9"]
fig, ax = plt.subplots(figsize=(11, 5))
# ── YOUR CODE HERE: plot each step response ────────────────────────────────────
# Loop over all_times, all_positions, and TARGET_ANGLES together.
# For each step i, plot all_times[i] vs all_positions[i] using colors[i] as the line color.
# Add a dashed horizontal line at the target angle.
# Label each curve with the target angle (e.g., label=f"Target: {TARGET_ANGLES[i]}°").
#
# Hint: for i, (t, pos, target) in enumerate(zip(all_times, all_positions, TARGET_ANGLES)):
# ax.plot(t, pos, color=colors[i], linewidth=2, label=f"Target: {target}°")
# ax.axhline(target, color=colors[i], linewidth=0.8, linestyle="--", alpha=0.5)
#
# ── YOUR CODE HERE ────────────────────────────────────────────────────────────
ax.set_xlabel("Time (s)", fontsize=11)
ax.set_ylabel("Motor position (°)", fontsize=11)
ax.set_title("Problem 1 — Step Response Through Five Target Angles",
fontsize=12, fontweight="bold")
ax.legend(fontsize=10)
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("problem1_step_response.png", dpi=150, bbox_inches="tight")
plt.show()
print("Plot saved as problem1_step_response.png")Look at your plot. For which step does the motor take the longest to settle? Does settling time increase with step size? Can you estimate the settling time (in seconds) for the largest step?
Answer: (write your answer here)
Problem 2 — Differential Drive: Forward and Turn¶
Goal: Use two motors to simulate a differential-drive wheel robot. In a differential-drive robot the two wheels are driven independently — the difference in speed between the two wheels determines the robot’s motion.
| Motion | Left wheel (Motor 1) | Right wheel (Motor 2) |
|---|---|---|
| Move forward | +speed | +speed (same magnitude) |
| Spin left in place | −speed | +speed |
| Spin right in place | +speed | −speed |
| Gradual turn | +slow | +fast (or vice versa) |
You will run two experiments and plot the commanded speed profile for each:
Forward: both motors at the same positive speed for 3 seconds
Turn: both motors at equal-but-opposite speeds for 3 seconds (spin in place)
Same helpers as before, in velocity mode:
| Function | What it does |
|---|---|
connect_motors_velocity(port, [id1, id2]) | Opens a connection to both motors and switches both to velocity (wheel) mode. Returns a bus object. |
write_speeds(bus, speed1, speed2) | Commands both motors to spin at speed1, speed2 simultaneously. |
Steps:
Connect both motors in velocity mode using
connect_motors_velocityFor the forward case: send the same speed to both motors, hold for
RUN_SEC, stopFor the turn case: send
+TURN_SPEEDto motor 1 and−TURN_SPEEDto motor 2, hold, stopDisconnect
Plot commanded speed vs. time for both motors in each case
What to fill in:
The
write_speeds(...)call for the forward caseThe
write_speeds(...)call for the turn case
import time
import numpy as np
# ── Parameters ────────────────────────────────────────────────────────────────
FORWARD_SPEED = 400 # speed for both motors when moving forward (0–1000)
TURN_SPEED = 400 # magnitude of speed for spinning in place (0–1000)
RUN_SEC = 3.0 # seconds to run each case
SAMPLE_HZ = 20 # samples per second (for recording the commanded profile)
n_samples = int(RUN_SEC * SAMPLE_HZ)
# Arrays to record the commanded speed at each time step
p2_spd1_fwd = np.zeros(n_samples)
p2_spd2_fwd = np.zeros(n_samples)
p2_spd1_trn = np.zeros(n_samples)
p2_spd2_trn = np.zeros(n_samples)
# ── Connect and switch both motors to velocity (wheel) mode ───────────────────
bus2 = connect_motors_velocity(PORT, [MOTOR_ID_1, MOTOR_ID_2])
# ── Case 1: Move forward — both motors at the same positive speed ─────────────
print("Case 1: Moving forward...")
# ── YOUR CODE HERE: send the same speed to both motors ────────────────────────
# write_speeds(bus2, ???, ???)
# ── YOUR CODE HERE ────────────────────────────────────────────────────────────
p2_spd1_fwd[:] = FORWARD_SPEED
p2_spd2_fwd[:] = FORWARD_SPEED
time.sleep(RUN_SEC)
write_speeds(bus2, 0, 0)
print(" Stopped. Waiting 2 s before turn case...")
time.sleep(2.0)
# ── Case 2: Spin in place — motors at equal and opposite speeds ───────────────
print("Case 2: Spinning in place...")
# ── YOUR CODE HERE: send +TURN_SPEED to motor1 and −TURN_SPEED to motor2 ──────
# write_speeds(bus2, ???, ???)
# ── YOUR CODE HERE ────────────────────────────────────────────────────────────
p2_spd1_trn[:] = +TURN_SPEED
p2_spd2_trn[:] = -TURN_SPEED
time.sleep(RUN_SEC)
write_speeds(bus2, 0, 0)
time.sleep(0.5)
# ── Disconnect ─────────────────────────────────────────────────────────────────
disconnect_motors(bus2)
print("Done. Run the next cell to plot.")import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(1, 2, figsize=(13, 4), sharey=True)
t_arr = np.linspace(0, RUN_SEC, n_samples)
# Case 1: Forward
ax = axes[0]
ax.step(t_arr, p2_spd1_fwd, where="post", color="#e74c3c", linewidth=2.5, label="Motor 1 (left)")
ax.step(t_arr, p2_spd2_fwd, where="post", color="#3498db", linewidth=2.5, linestyle="--", label="Motor 2 (right)")
ax.axhline(0, color="black", linewidth=0.8, linestyle=":", alpha=0.5)
ax.set_title("Case 1: Move Forward", fontsize=12, fontweight="bold")
ax.set_xlabel("Time (s)"); ax.set_ylabel("Commanded speed")
ax.legend(fontsize=10); ax.grid(True, alpha=0.3)
ax.set_ylim(-1100, 1100)
# Case 2: Turn
ax = axes[1]
ax.step(t_arr, p2_spd1_trn, where="post", color="#e74c3c", linewidth=2.5, label="Motor 1 (left)")
ax.step(t_arr, p2_spd2_trn, where="post", color="#3498db", linewidth=2.5, linestyle="--", label="Motor 2 (right)")
ax.axhline(0, color="black", linewidth=0.8, linestyle=":", alpha=0.5)
ax.set_title("Case 2: Spin in Place (Turn)", fontsize=12, fontweight="bold")
ax.set_xlabel("Time (s)")
ax.legend(fontsize=10); ax.grid(True, alpha=0.3)
fig.suptitle("Problem 2 — Differential Drive Speed Commands", fontsize=13, fontweight="bold")
plt.tight_layout()
plt.savefig("problem2_diff_drive.png", dpi=150, bbox_inches="tight")
plt.show()
print("Plot saved as problem2_diff_drive.png")If you wanted the robot to make a gradual left turn (arc) instead of spinning in place, how would you change the two speed values? What would happen if one speed were zero?
Answer: (write your answer here)
Problem 3 — Three Motors: Target Angles and Sine Wave Tracking¶
⚠️ This problem requires a third motor. You’ll assign it an ID and daisy-chain it onto the two motors from Part 2.
Goal: Extend the two-motor experiments to three motors. You will first move all three motors to different target angles simultaneously, then command each motor to track its own independent sine wave.
Before you start — assign an ID to the third motor:
Unplug both motors from the bus adapter.
Connect only the third motor to the adapter.
Run the re-ID cell below — it scans the bus to find the motor’s current ID, then prompts you to type the new ID (pick something not already used, e.g. 3).
Power-cycle the motor (unplug and re-plug the 12V supply) to save the new ID.
Reconnect all three motors in a daisy-chain: Adapter → Motor 1 → Motor 2 → Motor 3.
Good news: connect_motors, write_angles, read_angles, and disconnect_motors already work for any number of motors — the same functions you used for one motor in Part 1 and two motors in Part 2. There’s nothing new to write for the connection itself; you just pass a list of three IDs instead of two.
Steps:
Connect all three motors:
connect_motors(PORT, [MOTOR_ID_1, MOTOR_ID_2, MOTOR_ID_3])Move all three motors to different target angles simultaneously and print the actual vs. commanded positions.
Command all three motors to follow independent sine waves (different amplitude and frequency for each). Fill in the parameters for Motor 3.
Plot the tracking results for all three motors.
Key insight: sync_write and sync_read (which write_angles/read_angles use internally) address any number of motor IDs in a single packet. Going from two motors to three took no new code — just a longer list of IDs and one more angle per call.
Re-ID the third motor¶
This is the same re-ID procedure from Part 2’s Task 3.1, reused here for the third motor, using assign_motor_id from Lab2_helpers.py. It detects the motor’s current ID automatically and prompts you for the new one. Connect only the third motor before running this cell.
# Connect only the motor you want to re-ID before running this cell.
# This scans the bus to find the motor's current ID, then prompts you (in the
# input box that appears above the notebook) to type the new ID.
#
# existing_ids lists the IDs already assigned to the other motors on the bus --
# assign_motor_id refuses to reuse one of these, so you can't accidentally
# give two motors the same ID.
MOTOR_ID_3 = assign_motor_id(PORT, existing_ids=[MOTOR_ID_1, MOTOR_ID_2])
print("Ready for three motors: connect_motors(PORT, [MOTOR_ID_1, MOTOR_ID_2, MOTOR_ID_3])")import time
# MOTOR_ID_3 was set above when you re-IDed the third motor
# ── Target angles for each motor ──────────────────────────────────────────────
# Choose three different angles. Suggested range: −90° to +90°.
TARGET_M1 = 45.0 # degrees — motor 1
TARGET_M2 = -30.0 # degrees — motor 2
TARGET_M3 = 75.0 # degrees — motor 3 ← change this value
bus3 = connect_motors(PORT, [MOTOR_ID_1, MOTOR_ID_2, MOTOR_ID_3])
# Send all motors to 0° first
write_angles(bus3, 0.0, 0.0, 0.0)
time.sleep(2.0)
# ── YOUR CODE HERE: move all three motors to their target angles ───────────────
# Hint: use write_angles(bus3, TARGET_M1, TARGET_M2, TARGET_M3)
# ── YOUR CODE HERE ──────────────────────────────────────────────────────────────
time.sleep(2.0) # wait for all motors to arrive
# Read back the actual positions and report
a1, a2, a3 = read_angles(bus3)
print(f"Motor 1: target {TARGET_M1:+.1f}° actual {a1:+.1f}° error {a1-TARGET_M1:+.1f}°")
print(f"Motor 2: target {TARGET_M2:+.1f}° actual {a2:+.1f}° error {a2-TARGET_M2:+.1f}°")
print(f"Motor 3: target {TARGET_M3:+.1f}° actual {a3:+.1f}° error {a3-TARGET_M3:+.1f}°")
write_angles(bus3, 0.0, 0.0, 0.0)
time.sleep(1.5)
disconnect_motors(bus3)import time
import numpy as np
# ── Sine wave parameters ──────────────────────────────────────────────────────
P3_AMP1, P3_FREQ1 = 45.0, 0.3 # Motor 1: large swing, slow (0.3 Hz = one cycle per 3.3 s)
P3_AMP2, P3_FREQ2 = 30.0, 0.6 # Motor 2: medium swing, medium speed
# ── YOUR CODE HERE: choose amplitude (degrees) and frequency (Hz) for Motor 3 ─
P3_AMP3, P3_FREQ3 = None, None # replace None with numbers, e.g. 20.0 and 1.0
DURATION = 10.0 # total run time (seconds)
RATE_HZ = 50 # *target* command/recording rate (Hz) -- see note below
dt_p3 = 1.0 / RATE_HZ
# Lists to record the time, reference angles, and actual angles of all three motors
p3_t_list = []
p3_ref1_list = []; p3_act1_list = []
p3_ref2_list = []; p3_act2_list = []
p3_ref3_list = []; p3_act3_list = []
bus3 = connect_motors(PORT, [MOTOR_ID_1, MOTOR_ID_2, MOTOR_ID_3])
print(f"Motor 1: A={P3_AMP1}° f={P3_FREQ1} Hz")
print(f"Motor 2: A={P3_AMP2}° f={P3_FREQ2} Hz")
print(f"Motor 3: A={P3_AMP3}° f={P3_FREQ3} Hz")
print("Running — do not interrupt until 'Done' appears...")
t_start = time.time()
while True:
tick = time.time()
t_now = tick - t_start
if t_now >= DURATION:
break
r1 = P3_AMP1 * np.sin(2 * np.pi * P3_FREQ1 * t_now)
r2 = P3_AMP2 * np.sin(2 * np.pi * P3_FREQ2 * t_now)
# ── YOUR CODE HERE: compute r3 using P3_AMP3 and P3_FREQ3 (same formula as r1, r2) ─
r3 = None # replace None with the sine formula
# ── YOUR CODE HERE: send all three reference angles to the motors ─────────
# Hint: write_angles(bus3, r1, r2, r3)
# ── YOUR CODE HERE ──────────────────────────────────────────────────────────
a1, a2, a3 = read_angles(bus3)
p3_t_list.append(t_now)
p3_ref1_list.append(r1); p3_act1_list.append(a1)
p3_ref2_list.append(r2); p3_act2_list.append(a2)
p3_ref3_list.append(r3); p3_act3_list.append(a3)
elapsed = time.time() - tick
if elapsed < dt_p3:
time.sleep(dt_p3 - elapsed)
p3_t = np.array(p3_t_list)
p3_ref1 = np.array(p3_ref1_list); p3_act1 = np.array(p3_act1_list)
p3_ref2 = np.array(p3_ref2_list); p3_act2 = np.array(p3_act2_list)
p3_ref3 = np.array(p3_ref3_list); p3_act3 = np.array(p3_act3_list)
write_angles(bus3, 0.0, 0.0, 0.0)
time.sleep(1.5)
disconnect_motors(bus3)
achieved_hz = len(p3_t) / p3_t[-1] if len(p3_t) > 1 else float("nan")
print(f"Done. Recorded {len(p3_t)} samples over {p3_t[-1]:.2f} s "
f"(~{achieved_hz:.0f} Hz achieved vs. {RATE_HZ} Hz requested).")
print("Run the next cell to plot.")import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(3, 1, figsize=(12, 10), sharex=True)
datasets = [
(p3_ref1, p3_act1, P3_AMP1, P3_FREQ1, "#e74c3c", "Motor 1"),
(p3_ref2, p3_act2, P3_AMP2, P3_FREQ2, "#3498db", "Motor 2"),
(p3_ref3, p3_act3, P3_AMP3, P3_FREQ3, "#27ae60", "Motor 3"),
]
for ax, (ref, act, amp, freq, color, label) in zip(axes, datasets):
ax.plot(p3_t, ref, "b--", linewidth=1.5, label="Reference")
ax.plot(p3_t, act, color=color, linewidth=1.8, label="Actual")
rms = np.sqrt(np.mean((act - ref) ** 2))
ax.set_title(f"{label} — A={amp}°, f={freq} Hz (RMS error = {rms:.2f}°)",
fontweight="bold")
ax.set_ylabel("Angle (°)")
ax.legend(fontsize=9)
ax.grid(True, alpha=0.3)
ax.set_ylim(-amp * 1.5, amp * 1.5)
axes[-1].set_xlabel("Time (s)")
fig.suptitle("Problem 3 — Three Motors Following Independent Sine Waves",
fontsize=13, fontweight="bold")
plt.tight_layout()
plt.savefig("problem3_three_sines.png", dpi=150, bbox_inches="tight")
plt.show()
print("Plot saved as problem3_three_sines.png")Which motor has the largest tracking RMS error? Is it the one with the highest frequency, lowest frequency, or largest amplitude? Why?
Answer: (write your answer here)