Inverse kinematics and smooth motion with MoveIt 2
In the post on joint space and Cartesian space, I wrote inverse kinematics by hand for two joints. For six joints, that stops being a weekend exercise.
Watch: Smooth arm motion · Pick and place with a new gripper · Firmware: marlin-firmware on GitHub
In the post on joint space and Cartesian space, I wrote inverse kinematics by hand for two joints. For six joints, that stops being a weekend exercise. MoveIt 2 does it for you, along with collision checking, path planning and timing. This post is about what it does, and the part it doesn’t do: talking to a Marlin board.
Six joints, many answers
With two joints, a point usually has two solutions: elbow up or elbow down. A six-joint arm has to match a full pose, three numbers for position and three for orientation, and the choices multiply. On a typical arm with a wrist made of three joints, the shoulder can face the target or reach over backwards, the elbow can be up or down, and the wrist can be flipped or not. That’s up to eight ways to reach one pose.
Some poses have no answer at all: too far away, too close to the base, or an orientation the wrist can’t twist into.
This is why you usually ask an IK solver for the answer closest to where the arm is now, rather than any answer. A valid solution that flips the wrist 180° halfway through a pick is still a bad move.
Setting up MoveIt
The MoveIt Setup Assistant reads the robot’s URDF and generates a config package: which joints form the arm, which link is the gripper, named poses like “home”, and a few YAML files you’ll end up editing. Two of them matter most.
kinematics.yaml picks the IK solver:
arm: kinematics_solver: kdl_kinematics_plugin/KDLKinematicsPlugin kinematics_solver_search_resolution: 0.005 kinematics_solver_timeout: 0.005
KDL is the default. It’s numerical: it starts from a guess and iterates towards the target, which works for any chain of joints but can give up near joint limits or awkward poses. Other solver plugins, such as pick_ik, slot in by changing that one line.
joint_limits.yaml sets how fast each joint may move. These numbers should match what the firmware will actually allow, or MoveIt plans motions the arm can’t follow. The Marlin config allows 30°/s and 500°/s² per joint, and MoveIt wants radians:
joint_limits: joint_1: has_velocity_limits: true max_velocity: 0.5236 # 30°/s, Marlin’s DEFAULT_MAX_FEEDRATE has_acceleration_limits: true max_acceleration: 8.727 # 500°/s², Marlin’s DEFAULT_MAX_ACCELERATION
The generated file also sets default velocity and acceleration scaling to 10%, which is why first plans look so slow. That’s a sensible default for a new arm. Raise it once things work.
Planning in RViz
The demo launch file opens RViz with the arm and a draggable marker on the gripper. Drag it somewhere, press Plan, and MoveIt shows a ghost of the arm moving there. This is the best place to find out that a pose needs the wrist to flip, or that the planned path swings through the table, before any motor moves.
Behind that button, two things happen:
- A planner finds a path. The default, from the OMPL library, searches joint space for a sequence of poses that avoids collisions. It doesn’t care about time.
- Time is added. MoveIt then stretches the path in time so no joint exceeds the velocity and acceleration limits above. The result is a JointTrajectory: a list of points, each with joint angles in radians and a time_from_start.
When the gripper itself needs to move in a straight line, for an approach to a part or a final insert, MoveIt has Cartesian path planning, which does the “split the line into pieces and solve each one” trick from the earlier post, with collision checks.
The part MoveIt doesn’t do
MoveIt hands you a trajectory. Marlin wants G-code. Something in between has to translate, and get three details right.
Angles. URDF joints are in radians and measured from the URDF’s zero. Marlin’s axes are in degrees and measured from home. Each joint needs an offset and a direction:
import math
JOINTS = "XYZABC"
# Where each joint's URDF zero sits in Marlin's frame, and which way it turns.
# Example values: measure your own.
OFFSET_DEG = [90, 0, 90, 90, 90, 90]
SIGN = [1, 1, -1, 1, 1, 1]
def to_marlin(angles_rad):
return [o + s * math.degrees(a) for a, o, s in zip(angles_rad, OFFSET_DEG, SIGN)]
Speed. MoveIt gives a time for every point. Marlin wants a feedrate. With ARTICULATED_ROBOT_ARM, a move’s length is the size of the joint-space step (the square root of the sum of each joint’s change, squared), so the feedrate is that length divided by the time between points:
def trajectory_to_gcode(points):
"""points: list of (seconds, [six joint angles in radians])"""
lines = []
prev_t, prev = None, None
for t, angles in points:
target = to_marlin(angles)
if prev is not None:
dt = t - prev_t
length = math.sqrt(sum((a - b) ** 2 for a, b in zip(target, prev)))
if dt > 0 and length > 0:
feedrate = length / dt * 60 # units per minute
axes = " ".join(f"{j}{v:.2f}" for j, v in zip(JOINTS, target))
lines.append(f"G1 {axes} F{feedrate:.0f}")
prev_t, prev = t, target
return lines
Feeding it a trajectory is one line:
points = [
(p.time_from_start.sec + p.time_from_start.nanosec * 1e-9, list(p.positions))
for p in trajectory.points
]
Flow. Marlin holds 4 commands in its input buffer and 16 moves in its planner. The simplest safe protocol is to send a line, wait for ok, and send the next:
def send_all(port, lines):
for line in lines:
port.write((line + "\n").encode())
while True:
reply = port.readline().decode(errors="replace").strip()
if reply.startswith("ok"):
break
if reply.startswith("Error"):
raise RuntimeError(f"{line!r} -> {reply}")
# anything else, like "echo:busy: processing", just means wait
Why motion stutters, and how to keep it smooth
Marlin’s planner looks ahead across the moves in its buffer, so it can carry speed from one segment into the next instead of stopping at every point. That only works while the buffer has moves in it.
If the segments are very short in time, Marlin finishes them faster than the host can send the next ones, one ok at a time. The buffer drains, Marlin slows down to wait (its SLOWDOWN option does this on purpose), and the arm moves in little surges. On a video it looks like a shiver.
Things that help:
- Fewer, longer segments. A trajectory often has more points than the arm needs. Dropping points that are only a fraction of a degree apart cuts the traffic without changing the path much.
- Matching limits. If MoveIt’s limits are higher than Marlin’s, Marlin silently slows each move down, and the timing MoveIt planned no longer holds.
- Streaming ahead. Marlin’s ADVANCED_OK option (off in this config) adds buffer space to each ok, so a host can keep several lines in flight instead of waiting for each one.
None of this is glamorous, but it’s the difference between an arm that moves like a robot from a film and one that moves like it’s thinking about every step.