Everything so far has been a robot that drives. This chapter is about one that reaches: a small arm of two links and three hobby servos that picks something up at one point and puts it down at another. The mathematics is old and short (a triangle and the law of cosines); what makes it a chapter for the Uno is what surrounds it: the servos take whole degrees or microseconds, the library that drives them takes a timer and a pin you may have promised to something else, the trigonometry is slow on a chip with no floating-point unit, and an arm that moves its joints together does not move its tip in a straight line.
The chapter builds the arm as plain functions (forward and inverse kinematics), a trapezoidal speed profile, a set of lookup tables in flash, and a pick-and-place cycle that is first run on the simulator and then written as a sketch for the Uno. As in the rest of the course, every number comes from running the code, and what was not run is said so. The arm itself is an assumption: no arm was built, and the Uno never drove a servo.
What was run, and what was not
Run on a PC (g++ 16.2, C++11, -Wall -Wextra -pedantic): every experiment with an output under it and the three challenge solutions, on a simulated arm: links of 100 and 80 mm, a table at −40 mm, joint limits of 120°/s and 400°/s², and 0.8° of play in each joint are assumptions I chose, not measurements.
Read from source: what the Servo library does (its pulse range, its integer-degree write, its 20 ms refresh, the timer it takes) comes from the source of Servo 1.3.0 that I installed with arduino-cli for this chapter; I read it, I did not run it on a board.
Compiled for the Uno, not run (arduino-cli, core arduino:avr 1.8.8, --warnings all): the eight-variant cost-test sketch and robot_ch11.ino; instruction and library-call counts come from avr-objdump, sizes from the compiler and avr-nm.
Nothing was attached to a board and no time was measured. “Cost” means bytes of flash and RAM and the number of instructions and library calls, never seconds; the claims about real servos (speed, jitter, torque, how a pulse becomes an angle) are not tested here.
1. An arm is a function from angles to a point
A planar arm with two links is described by three numbers: the lengths l1 and l2 and, for a given pose, the two joint angles t1 (the shoulder, measured from the horizontal) and t2 (the elbow, relative to the first link). The tip is where the two links add up: x = l1 cos t1 + l2 cos(t1 + t2) and y = l1 sin t1 + l2 sin(t1 + t2). That is forward kinematics, a function with one answer. The question a robot actually asks is the reverse: given the point, what angles? That is inverse kinematics, and it can have two answers (the elbow up or down) or none (the point is too far, or too close).
In Python
On the Uno in C++
math.acos(c) raises ValueError if c is outside [−1, 1]
acosf returns nan and carries on; the function must test and say “unreachable” with a return value
a list of points, for x, y in path:
a fixed table of waypoints in flash or RAM, indexed by a leg counter
time.sleep(0.02) in a loop to move a servo a step
the scheduler of Programming for Robotics with Arduino C++ 1 calls the control task every 20 ms; nothing blocks
a servo library on a Linux board sets the angle in floats
a table of uint16_t in flash, read with pgm_read_word and interpolated by hand
any number of servos on any pins
one timer (Timer1) drives them; the pins you promised to something else are gone
2. Forward and inverse kinematics as functions
All of the chapter’s code is in one header, arm.h: plain C++11 with no heap and no Arduino calls, so the same file runs on the PC and on the Uno. The inverse kinematics uses the law of cosines: cos t2 = (x² + y² − l1² − l2²) / (2 l1 l2). If that is outside [−1, 1] there is no triangle, and the function returns false rather than a number; otherwise t2 is plus or minus the angle whose cosine that is (the sign is the elbow up or down), and t1 is the direction of the point minus the angle the first link makes inside the triangle. Here is the whole header; the parts after the inverse kinematics are used in the later sections:
// arm.h -- a two-link planar arm in plain functions (Programming for Robotics with Arduino C++ 11). Plain C++11: no heap, no Arduino calls, so the same file runs on the PC and the Uno.
// Convention: shoulder angle t1 from the +x axis (counter-clockwise positive), elbow angle t2 relative to the first link; x forward, y up, all lengths in millimetres, angles in radians.
// x = l1 cos(t1) + l2 cos(t1 + t2) y = l1 sin(t1) + l2 sin(t1 + t2)
#pragma once
#include <stdint.h>
#include <math.h>
#ifdef __AVR__
#include <avr/pgmspace.h>
#else
#define PROGMEM
#define pgm_read_word(p) (*(p))
#endif
struct Arm { float l1, l2; };
inline void fk(const Arm& a, float t1, float t2, float& x, float& y) {
x = a.l1 * cosf(t1) + a.l2 * cosf(t1 + t2);
y = a.l1 * sinf(t1) + a.l2 * sinf(t1 + t2);
}
// ---- inverse kinematics with the library's acosf / atan2f ----
// law of cosines: cos(t2) = (x^2 + y^2 - l1^2 - l2^2) / (2 l1 l2). Outside [-1, 1] the point is out of reach: return false, never a number.
// elbow_up: the elbow is above the line from the shoulder to the tip (t2 < 0 with this convention).
inline bool ik(const Arm& a, float x, float y, bool elbow_up, float& t1, float& t2) {
float c2 = (x * x + y * y - a.l1 * a.l1 - a.l2 * a.l2) / (2.0f * a.l1 * a.l2);
if (c2 > 1.0f || c2 < -1.0f) return false;
float s2 = sqrtf(1.0f - c2 * c2);
if (elbow_up) s2 = -s2;
t2 = atan2f(s2, c2); // = +-acos(c2)
t1 = atan2f(y, x) - atan2f(a.l2 * s2, a.l1 + a.l2 * c2);
return true;
}
// ---- the same, with lookup tables in flash instead of acosf / atan2f ----
// A table has n + 1 entries of 1e-4 radian (uint16_t) for a variable running over [0, 1] in n equal steps; between the entries the value is a linear interpolation.
inline float table_interp(const uint16_t* t, uint8_t n, float u) {
float pos = u * (float)n;
int16_t i = (int16_t)pos;
if (i < 0) i = 0;
if (i > (int16_t)n - 1) i = (int16_t)n - 1;
float frac = pos - (float)i;
float v0 = (float)pgm_read_word(&t[i]), v1 = (float)pgm_read_word(&t[i + 1]);
return (v0 + (v1 - v0) * frac) * 1.0e-4f;
}
inline float acos_lut(float c, const uint16_t* t, uint8_t n) { // t[k] = acos(-1 + 2 k / n) * 1e4
return table_interp(t, n, (c + 1.0f) * 0.5f);
}
inline float atan2_lut(float y, float x, const uint16_t* t, uint8_t n) { // t[k] = atan(k / n) * 1e4; the octant is folded back by hand
float ax = fabsf(x), ay = fabsf(y);
if (ax == 0.0f && ay == 0.0f) return 0.0f;
bool swap = ay > ax;
float a = table_interp(t, n, swap ? ax / ay : ay / ax);
if (swap) a = 1.5707964f - a;
if (x < 0.0f) a = 3.1415927f - a;
return y < 0.0f ? -a : a;
}
inline bool ik_lut(const Arm& a, float x, float y, bool elbow_up, float& t1, float& t2, const uint16_t* acos_t, const uint16_t* atan_t, uint8_t n) {
float c2 = (x * x + y * y - a.l1 * a.l1 - a.l2 * a.l2) / (2.0f * a.l1 * a.l2);
if (c2 > 1.0f || c2 < -1.0f) return false;
float s2 = sqrtf(1.0f - c2 * c2);
if (elbow_up) s2 = -s2;
t2 = acos_lut(c2, acos_t, n);
if (elbow_up) t2 = -t2;
t1 = atan2_lut(y, x, atan_t, n) - atan2_lut(a.l2 * s2, a.l1 + a.l2 * c2, atan_t, n);
return true;
}
// ---- forward kinematics in integers, for servos that take whole degrees ----
// sine of a whole number of degrees: the table SIN_Q15 holds 91 entries for 0..90 degrees (32768 = 1.0); every other angle is folded onto them and the result is Q14 (16384 = 1.0) so it fits an int16_t. Tips come out in tenths of a millimetre.
extern const uint16_t SIN_Q15[91] PROGMEM;
inline int16_t sin_q14(int16_t deg) {
deg %= 360; if (deg < 0) deg += 360;
bool neg = deg >= 180; if (neg) deg -= 180;
if (deg > 90) deg = 180 - deg;
int16_t v = (int16_t)(pgm_read_word(&SIN_Q15[deg]) >> 1); // Q14 so that 1.0 fits an int16_t
return neg ? -v : v;
}
inline int16_t cos_q14(int16_t deg) { return sin_q14(deg + 90); }
inline void fk_int(int16_t l1_mm, int16_t l2_mm, int16_t t1_deg, int16_t t2_deg, int16_t& x_tenth, int16_t& y_tenth) {
int32_t x = (int32_t)l1_mm * cos_q14(t1_deg) + (int32_t)l2_mm * cos_q14(t1_deg + t2_deg);
int32_t y = (int32_t)l1_mm * sin_q14(t1_deg) + (int32_t)l2_mm * sin_q14(t1_deg + t2_deg);
x_tenth = (int16_t)((x * 10) >> 14); y_tenth = (int16_t)((y * 10) >> 14);
}
// ---- a trapezoidal speed profile: accelerate at a, cruise at v, brake at a; a short move never reaches v and is a triangle ----
struct Trap {
float d, v, a, ta, tc, T, sign;
void plan(float dist, float vmax, float amax) {
sign = dist < 0.0f ? -1.0f : 1.0f; d = fabsf(dist); a = amax;
if (d == 0.0f) { v = 0.0f; ta = tc = T = 0.0f; return; }
if (d < vmax * vmax / amax) { v = sqrtf(amax * d); ta = v / amax; tc = 0.0f; }
else { v = vmax; ta = vmax / amax; tc = (d - vmax * ta) / vmax; }
T = 2.0f * ta + tc;
}
float pos(float t) const {
if (t <= 0.0f) return 0.0f;
if (t >= T) return sign * d;
float p;
if (t < ta) p = 0.5f * a * t * t;
else if (t < ta + tc) p = 0.5f * a * ta * ta + v * (t - ta);
else { float r = T - t; p = d - 0.5f * a * r * r; }
return sign * p;
}
float vel(float t) const {
if (t <= 0.0f || t >= T) return 0.0f;
float s;
if (t < ta) s = a * t; else if (t < ta + tc) s = v; else s = a * (T - t);
return sign * s;
}
};
// two joints that start and finish together: the one that moves further sets the time, the other runs the same shape with its limits scaled down
inline void plan_sync(Trap& j0, Trap& j1, float d0, float d1, float vmax, float amax) {
float m0 = fabsf(d0), m1 = fabsf(d1);
if (m0 >= m1) { j0.plan(d0, vmax, amax); float s = m0 > 0.0f ? m1 / m0 : 0.0f; j1.plan(d1, vmax * s, amax * s); if (s == 0.0f) { j1.T = j0.T; } }
else { j1.plan(d1, vmax, amax); float s = m1 / m0; j0.plan(d0, vmax * s, amax * s); }
}
The first experiment asks whether the two functions agree, and what the reachable region looks like. The arm has links of 100 and 80 mm (assumed). It can reach any point between a distance of 20 mm (the folded arm, l1 − l2) and 180 mm (the straight arm, l1 + l2) from the shoulder: a ring. Part B turns the angles into what a servo can say: whole degrees through write(int), or whole microseconds through writeMicroseconds (10.31 µs per degree with the library’s 544–2400 µs range, so 1 µs is 0.097°), and measures how far the tip lands from the asked-for point. Part C looks at the edge of the ring.
// e_kin.cpp -- forward and inverse kinematics of a 2-link arm, l1 = 100 mm, l2 = 80 mm (host build; the arm is an assumption: no real arm was built or measured).
// Part A: ik() over a 1 mm grid of points in the 360 x 360 mm square around the shoulder: which are reachable, and does fk(ik(p)) return p? Both elbow settings.
// Part B: a servo takes whole degrees (Servo::write(int)) or microseconds (writeMicroseconds, 1 us = 0.097 degree with the library's 544..2400 us for 0..180 degrees):
// round the joint angles to those steps and measure how far the tip lands from where it was asked to go, over the reachable points with y >= -40 mm and r <= 170 mm.
// Part C: the tip moves outward along y = 0 at 50 mm/s: the joint speeds that takes, near the edge of the workspace (a singularity: the arm is straight).
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "arm.h"
static const float D2R = 3.14159265f / 180.0f, R2D = 180.0f / 3.14159265f;
static float quant(float rad, float step_deg) { return std::round(rad * R2D / step_deg) * step_deg * D2R; }
int main() {
const Arm arm = {100.0f, 80.0f};
std::printf("part A: ik() on a 1 mm grid, 361 x 361 points around the shoulder\n");
for (int up = 1; up >= 0; --up) {
long ok = 0; double worst = 0.0;
for (int yi = -180; yi <= 180; ++yi)
for (int xi = -180; xi <= 180; ++xi) {
float t1, t2;
if (!ik(arm, (float)xi, (float)yi, up != 0, t1, t2)) continue;
++ok;
float x, y; fk(arm, t1, t2, x, y);
double e = std::hypot(x - xi, y - yi); if (e > worst) worst = e;
}
std::printf(" elbow %-4s reachable %6ld points, worst error of fk(ik(p)) = %.5f mm\n", up ? "up" : "down", ok, worst);
}
std::printf(" area of the ring between r = 20 and r = 180 mm: %.0f mm^2 (the count of points should be close)\n", 3.14159265 * (180.0 * 180.0 - 20.0 * 20.0));
{ float t1, t2; bool a = ik(arm, 181.0f, 0.0f, true, t1, t2), b = ik(arm, 19.0f, 0.0f, true, t1, t2), c = ik(arm, 180.0f, 0.0f, true, t1, t2);
std::printf(" (181, 0): %s; (19, 0): %s; (180, 0): %s (exactly straight)\n", a ? "reachable" : "unreachable", b ? "reachable" : "unreachable", c ? "reachable" : "unreachable"); }
std::printf("\npart B: tip error from the servo's step (elbow up, working area y >= -40 mm, r <= 170 mm)\n");
std::printf(" step mean error (mm) worst error (mm) points\n");
struct { const char* name; float step; } modes[3] = {{"1 degree (write(int))", 1.0f}, {"1 microsecond (0.097 deg)", 0.0970f}, {"0.5 us timer tick (0.048 deg)", 0.0485f}};
for (int m = 0; m < 3; ++m) {
double sum = 0, worst = 0; long n = 0;
for (int yi = -40; yi <= 170; ++yi)
for (int xi = -170; xi <= 170; ++xi) {
if (xi * xi + yi * yi > 170 * 170) continue;
float t1, t2;
if (!ik(arm, (float)xi, (float)yi, true, t1, t2)) continue;
float x, y; fk(arm, quant(t1, modes[m].step), quant(t2, modes[m].step), x, y);
double e = std::hypot(x - xi, y - yi); sum += e; if (e > worst) worst = e; ++n;
}
std::printf(" %-27s %15.3f %16.3f %6ld\n", modes[m].name, sum / n, worst, n);
}
std::printf("\npart C: tip moving outward along y = 0 at 50 mm/s: the joint speeds that needs\n");
std::printf(" tip x (mm) shoulder (deg/s) elbow (deg/s)\n");
for (float x : {40.0f, 100.0f, 150.0f, 170.0f, 178.0f, 179.5f, 179.95f}) {
float a1 = 0, a2 = 0, b1 = 0, b2 = 0;
ik(arm, x, 0.0f, true, a1, a2); ik(arm, x + 0.01f, 0.0f, true, b1, b2);
std::printf(" %10.2f %16.1f %13.1f\n", x, std::fabs(b1 - a1) / 0.01f * 50.0f * R2D, std::fabs(b2 - a2) / 0.01f * 50.0f * R2D);
}
return 0;
}
part A: ik() on a 1 mm grid, 361 x 361 points around the shoulder
elbow up reachable 100520 points, worst error of fk(ik(p)) = 0.00006 mm
elbow down reachable 100520 points, worst error of fk(ik(p)) = 0.00006 mm
area of the ring between r = 20 and r = 180 mm: 100531 mm^2 (the count of points should be close)
(181, 0): unreachable; (19, 0): unreachable; (180, 0): reachable (exactly straight)
part B: tip error from the servo's step (elbow up, working area y >= -40 mm, r <= 170 mm)
step mean error (mm) worst error (mm) points
1 degree (write(int)) 0.629 2.069 57780
1 microsecond (0.097 deg) 0.061 0.199 57780
0.5 us timer tick (0.048 deg) 0.030 0.100 57780
part C: tip moving outward along y = 0 at 50 mm/s: the joint speeds that needs
tip x (mm) shoulder (deg/s) elbow (deg/s)
40.00 23.6 37.7
100.00 12.5 39.1
150.00 24.4 58.1
170.00 42.7 97.5
178.00 95.6 215.6
179.50 191.9 432.1
179.95 637.0 1433.2
The functions agree: over 100,520 reachable points the round trip fk(ik(p)) is within 0.00006 mm, with the elbow up or down, and the count of reachable points (100,520) is close to the area of the ring (100,531 mm²). The points outside are refused: (181, 0) and (19, 0) are unreachable. The point (180, 0), exactly straight, is reported reachable, which depends on a floating-point value landing at 1.0 and not above it; an arm that is asked for its full length is asking for trouble anyway.
The servo’s step is the arm’s resolution. Whole degrees put the tip 0.63 mm off on average and 2.07 mm at worst, in the working area. Microseconds are ten times better (0.06 and 0.20 mm), and the library’s own half-microsecond timer tick would be 0.03 and 0.10 mm. The tip error is roughly the reach times the angular step, so it is worst where the arm is longest, and a Python script that sets “angle = 47.3” on a PC has hidden that the servo would have taken 47.
The edge of the workspace is a trap. To move the tip outward along a line at 50 mm/s the joints need 12–58°/s between 40 and 150 mm from the shoulder, 43 and 98°/s at 170 mm, and 637 and 1,433°/s at 179.95 mm, a few hundredths of a millimetre before the arm is straight. An arm that is told to reach a point near its full length must either slow down to a crawl or fail; a planner keeps its waypoints away from the singularity.
3. What the Servo library does
I installed the Servo library (version 1.3.0) and read its source, because the chapter’s claims about it are claims about code. What it does, with the lines it comes from:
The pulse range.MIN_PULSE_WIDTH 544 and MAX_PULSE_WIDTH 2400 in Servo.h; write(int value) for 0–180 does map(value, 0, 180, SERVO_MIN(), SERVO_MAX()) in avr/Servo.cpp. So an angle in whole degrees is 10.31 µs per degree, rounded by integer map.
The clock. Timer1 with a prescaler of 8 (TCCR1B = _BV(CS11)): a tick is 0.5 µs at 16 MHz, so a pulse width is held to half a microsecond. writeMicroseconds(int) takes whole microseconds, and clips the value to the (trimmable) range.
The refresh.REFRESH_INTERVAL 20000: a 20 ms frame. The servos on one timer are pulsed one after the other inside it, up to 12 per timer (SERVOS_PER_TIMER 12), by an interrupt on Timer1 that calls digitalWrite. A command written during a frame takes effect at the servo’s next pulse, so there is no point commanding faster than 50 Hz.
The timer it takes.attach sets TCCR1A = 0 (normal counting mode) on the first servo. On an Uno, pins 9 and 10 are the outputs of Timer1’s hardware PWM (the pin table of Programming for Robotics with Arduino C++ 2), so from the first attach I expect analogWrite on 9 and 10 to stop working. That follows from the source and the pin table; I did not run it. The robot’s motors are on pins 5 and 6 (Timer0), which are not touched.
Two consequences are measurable without a board. The pin budget: the plan of Programming for Robotics with Arduino C++ 2 uses every pin except 9 and 10 (0 and 1 are the USB link, 18 and 19 the I2C bus of Programming for Robotics with Arduino C++ 10), so an arm with three servos (shoulder, elbow, gripper) must give up a pin: robot_ch11.ino takes pin 13, the LED, for the gripper, because the Servo library will drive any digital pin. And the cost in bytes, in section 5.
4. A trapezoidal speed profile
A servo commanded straight to a new angle moves as fast as it can, and a real arm shakes when it is slammed. The usual remedy is a trapezoidal profile: accelerate at a constant rate, cruise at the top speed, brake at the same rate. The position at time t is a pair of parabolas and a line; Trap in arm.h computes it with no loop. A short move never reaches the top speed and becomes a triangle: the peak speed is sqrt(a d). Two joints that must arrive together are synchronised: the joint with the longer move sets the time, and the other runs the same shape with its speed and acceleration limits scaled by the ratio of the distances. The experiment (the limits of 120°/s and 400°/s² are assumed) checks the maths numerically, shows what a servo that takes whole degrees does to a slow profile, and synchronises two joints:
// e_trap.cpp -- trapezoidal speed profiles for a joint, and what a servo that takes whole degrees does to them (host build; limits are assumed: 120 deg/s, 400 deg/s^2).
// Part A: moves of several lengths: acceleration time, cruise time, total time, peak speed, and a numerical check (integrate the speed; find the largest acceleration by differences).
// Part B: a slow move of 30 degrees at 20 deg/s, commanded at 50 Hz (every 20 ms), rounded to whole degrees and to 0.1 degree: the speed between two commands.
// Part C: two joints moving 60 and 15 degrees, synchronised: both finish together.
#include <cstdio>
#include <cmath>
#include <initializer_list>
#include "arm.h"
int main() {
const float VMAX = 120.0f, AMAX = 400.0f;
std::printf("part A: one joint, vmax %.0f deg/s, amax %.0f deg/s^2\n", VMAX, AMAX);
std::printf(" move (deg) accelerate (s) cruise (s) total (s) peak speed (deg/s) shape integral of speed (deg) largest acceleration (deg/s^2)\n");
for (float d : {5.0f, 10.0f, 20.0f, 36.0f, 40.0f, 90.0f, 180.0f}) {
Trap t; t.plan(d, VMAX, AMAX);
double integ = 0, amax_seen = 0; float prev_v = 0.0f;
for (int i = 1; i <= (int)(t.T * 1000.0f) + 1; ++i) {
float tt = i * 0.001f, v = t.vel(tt);
integ += v * 0.001; double a = std::fabs(v - prev_v) / 0.001; if (a > amax_seen) amax_seen = a; prev_v = v;
}
std::printf(" %10.0f %14.3f %10.3f %9.3f %18.1f %-9s %23.3f %30.0f\n", d, t.ta, t.tc, t.T, t.v, t.tc > 0 ? "trapezoid" : "triangle", integ, amax_seen);
}
std::printf("\npart B: a move of 30 degrees at 20 deg/s (acceleration 400), a new command every 20 ms\n");
std::printf(" command rounded to updates updates with no motion updates with 1 deg fastest speed seen between commands (deg/s) slowest nonzero (deg/s)\n");
for (int mode = 0; mode < 2; ++mode) {
Trap t; t.plan(30.0f, 20.0f, AMAX);
int n = 0, zero = 0, one = 0; double fastest = 0, slowest = 1e9; double prev = 0.0;
for (int i = 1; (i * 0.02f) <= t.T + 0.0001f; ++i) {
double p = t.pos(i * 0.02f);
double q = mode == 0 ? std::round(p) : std::round(p * 10.0) / 10.0;
double step = q - prev; prev = q; ++n;
double sp = std::fabs(step) / 0.02;
if (step == 0.0) ++zero; else if (std::fabs(step - 1.0) < 1e-9) ++one;
if (sp > fastest) fastest = sp;
if (step != 0.0 && sp < slowest) slowest = sp;
}
std::printf(" %-18s %8d %22d %18d %43.1f %23.1f\n", mode == 0 ? "whole degrees" : "0.1 degree", n, zero, one, fastest, slowest);
}
std::printf("\npart C: two joints, 60 and 15 degrees, synchronised (vmax %.0f, amax %.0f for the longer one)\n", VMAX, AMAX);
{ Trap a, b; plan_sync(a, b, 60.0f, 15.0f, VMAX, AMAX);
std::printf(" joint 0: T = %.4f s, peak %.1f deg/s; joint 1: T = %.4f s, peak %.1f deg/s\n", a.T, a.v, b.T, b.v);
for (float t : {0.0f, 0.1f, 0.2f, 0.3f, 0.4f, a.T}) std::printf(" t = %.3f s joint 0 at %7.3f deg joint 1 at %7.3f deg (fraction %.4f and %.4f)\n", t, a.pos(t), b.pos(t), a.pos(t) / 60.0f, b.pos(t) / 15.0f); }
return 0;
}
part A: one joint, vmax 120 deg/s, amax 400 deg/s^2
move (deg) accelerate (s) cruise (s) total (s) peak speed (deg/s) shape integral of speed (deg) largest acceleration (deg/s^2)
5 0.112 0.000 0.224 44.7 triangle 5.000 400
10 0.158 0.000 0.316 63.2 triangle 10.000 400
20 0.224 0.000 0.447 89.4 triangle 20.000 400
36 0.300 0.000 0.600 120.0 triangle 36.000 400
40 0.300 0.033 0.633 120.0 trapezoid 40.000 400
90 0.300 0.450 1.050 120.0 trapezoid 90.000 400
180 0.300 1.200 1.800 120.0 trapezoid 180.000 400
part B: a move of 30 degrees at 20 deg/s (acceleration 400), a new command every 20 ms
command rounded to updates updates with no motion updates with 1 deg fastest speed seen between commands (deg/s) slowest nonzero (deg/s)
whole degrees 77 47 30 50.0 50.0
0.1 degree 77 0 0 20.0 5.0
part C: two joints, 60 and 15 degrees, synchronised (vmax 120, amax 400 for the longer one)
joint 0: T = 0.8000 s, peak 120.0 deg/s; joint 1: T = 0.8000 s, peak 30.0 deg/s
t = 0.000 s joint 0 at 0.000 deg joint 1 at 0.000 deg (fraction 0.0000 and 0.0000)
t = 0.100 s joint 0 at 2.000 deg joint 1 at 0.500 deg (fraction 0.0333 and 0.0333)
t = 0.200 s joint 0 at 8.000 deg joint 1 at 2.000 deg (fraction 0.1333 and 0.1333)
t = 0.300 s joint 0 at 18.000 deg joint 1 at 4.500 deg (fraction 0.3000 and 0.3000)
t = 0.400 s joint 0 at 30.000 deg joint 1 at 7.500 deg (fraction 0.5000 and 0.5000)
t = 0.800 s joint 0 at 60.000 deg joint 1 at 15.000 deg (fraction 1.0000 and 1.0000)
The profile is exact: the integral of the speed is the distance in every case, and the largest acceleration found by differences is the limit. The break between a triangle and a trapezoid is at 36° (vmax² / amax). Part B is the unexpected one. A move of 30° at 20°/s, commanded every 20 ms and rounded to whole degrees, becomes 47 updates in which nothing moves and 30 in which the joint jumps 1°: a speed of 50°/s, two and a half times the one asked for, in a stop-and-go pattern. Rounded to 0.1° (a bit more than 1 µs) the speed varies smoothly between 5 and 20°/s. A slow move is where whole degrees hurt, and writeMicroseconds with a float angle is the remedy. Part C: the joints that move 60° and 15° arrive together at 0.800 s, and at every time the fractions of the distance covered are equal (0.0333 and 0.0333 at 0.1 s): the joints start and stop together.
5. Lookup tables in flash
The inverse kinematics needs three angles: the elbow (an arc-cosine, or the arc-tangent of its sine and cosine, as ik() does) and two directions (arc-tangents). On a chip with no floating-point unit they are library routines, and an obvious idea is to replace them by a table: precompute the function at evenly spaced points, store it in flash, and interpolate. ik_lut() in arm.h does this: acos over [−1, 1] and atan over [0, 1] (the octant is folded back by hand), 64 steps each, values in units of 10−4 rad in uint16_t. The tables are made on the PC and written as C++ source, so there is nothing to compute at start-up, and on the AVR they are PROGMEM and take no RAM (the hard lesson of Programming for Robotics with Arduino C++ 9: a const array is RAM unless it says otherwise).
// e_gen.cpp -- writes tables.h: the lookup tables of arm.h as C++ source, generated on the PC (host build).
// ACOS_T: acos(-1 + 2 k / 64) in units of 1e-4 rad, 65 entries; ATAN_T: atan(k / 64) in 1e-4 rad, 65 entries; SIN_Q15: sin(0..90 degrees) times 32768, 91 entries.
#include <cstdio>
#include <cmath>
#include "arm.h"
int main() {
FILE* f = std::fopen("tables.h", "w");
std::fprintf(f, "// tables.h -- generated by e_gen.cpp: do not edit. Lookup tables for arm.h, in flash on the Uno.\n#pragma once\n#include \"arm.h\"\n");
std::fprintf(f, "const uint8_t LUT_N = 64;\n");
std::fprintf(f, "const uint16_t ACOS_T[65] PROGMEM = {");
for (int k = 0; k <= 64; ++k) std::fprintf(f, "%s%ld", k ? ", " : "", std::lround(std::acos(-1.0 + 2.0 * k / 64.0) * 1e4));
std::fprintf(f, "};\nconst uint16_t ATAN_T[65] PROGMEM = {");
for (int k = 0; k <= 64; ++k) std::fprintf(f, "%s%ld", k ? ", " : "", std::lround(std::atan(k / 64.0) * 1e4));
std::fprintf(f, "};\nconst uint16_t SIN_Q15[91] PROGMEM = {");
for (int d = 0; d <= 90; ++d) std::fprintf(f, "%s%ld", d ? ", " : "", std::lround(std::sin(d * 3.14159265358979323846 / 180.0) * 32768.0));
std::fprintf(f, "};\n");
std::fclose(f);
std::printf("tables.h written: ACOS_T and ATAN_T of 65 entries (130 bytes each), SIN_Q15 of 91 entries (182 bytes): 442 bytes of flash in all\n");
return 0;
}
tables.h written: ACOS_T and ATAN_T of 65 entries (130 bytes each), SIN_Q15 of 91 entries (182 bytes): 442 bytes of flash in all
How big must a table be? The experiment builds tables of several sizes and runs ik_lut() over the whole ring, feeding the result to the ordinary fk():
// e_lut.cpp -- inverse kinematics with lookup tables instead of acosf and atan2f: how big must the tables be? (host build; arm l1 = 100 mm, l2 = 80 mm, assumed)
// For each table size n the tables are built here at run time and ik_lut() from arm.h is run over every reachable point of a 1 mm grid (elbow up); the angles it returns are fed
// to the ordinary fk(), and the distance from the asked-for point is the tip error. The flash cost is 2 tables x (n + 1) entries x 2 bytes.
// Then, for n = 64, where the error sits: by the distance of the point from the shoulder.
#include <cstdio>
#include <cmath>
#include <vector>
#include <initializer_list>
#include "arm.h"
static void build(int n, std::vector<uint16_t>& ac, std::vector<uint16_t>& at) {
ac.resize(n + 1); at.resize(n + 1);
for (int k = 0; k <= n; ++k) { ac[k] = (uint16_t)std::lround(std::acos(-1.0 + 2.0 * k / n) * 1e4); at[k] = (uint16_t)std::lround(std::atan((double)k / n) * 1e4); }
}
int main() {
const Arm arm = {100.0f, 80.0f};
std::printf("tip error of ik_lut() against the table size, over the reachable 1 mm grid (elbow up), r from 20 to 180 mm\n");
std::printf(" entries n flash (bytes) mean error (mm) worst error (mm) worst error for 40 <= r <= 170 (mm) worst at r (mm)\n");
std::vector<uint16_t> ac, at;
for (int n : {8, 16, 32, 64, 128}) {
build(n, ac, at);
double sum = 0, worst = 0, worst170 = 0, worst_r = 0; long cnt = 0;
for (int yi = -180; yi <= 180; ++yi)
for (int xi = -180; xi <= 180; ++xi) {
float t1 = 0, t2 = 0;
if (!ik_lut(arm, (float)xi, (float)yi, true, t1, t2, ac.data(), at.data(), (uint8_t)n)) continue;
float x, y; fk(arm, t1, t2, x, y);
double e = std::hypot(x - xi, y - yi), r = std::hypot((double)xi, (double)yi);
sum += e; ++cnt;
if (e > worst) { worst = e; worst_r = r; }
if (r >= 40.0 && r <= 170.0 && e > worst170) worst170 = e;
}
std::printf(" %9d %13d %15.4f %16.3f %32.3f %15.1f\n", n, 2 * 2 * (n + 1), sum / cnt, worst, worst170, worst_r);
}
std::printf("\nn = 64: the worst tip error in rings of the distance r from the shoulder\n");
std::printf(" r from-to (mm) points mean error (mm) worst error (mm)\n");
build(64, ac, at);
const double edges[] = {20, 40, 80, 120, 160, 170, 175, 178, 180.5};
for (int b = 0; b < 8; ++b) {
double sum = 0, worst = 0; long cnt = 0;
for (int yi = -180; yi <= 180; ++yi)
for (int xi = -180; xi <= 180; ++xi) {
double r = std::hypot((double)xi, (double)yi);
if (r < edges[b] || r >= edges[b + 1]) continue;
float t1 = 0, t2 = 0;
if (!ik_lut(arm, (float)xi, (float)yi, true, t1, t2, ac.data(), at.data(), 64)) continue;
float x, y; fk(arm, t1, t2, x, y);
double e = std::hypot(x - xi, y - yi); sum += e; ++cnt; if (e > worst) worst = e;
}
std::printf(" %5.0f - %-6.1f %6ld %15.4f %16.3f\n", edges[b], edges[b + 1], cnt, cnt ? sum / cnt : 0.0, worst);
}
return 0;
}
tip error of ik_lut() against the table size, over the reachable 1 mm grid (elbow up), r from 20 to 180 mm
entries n flash (bytes) mean error (mm) worst error (mm) worst error for 40 <= r <= 170 (mm) worst at r (mm)
8 36 2.5255 14.106 13.832 177.3
16 68 0.9348 9.982 6.924 178.5
32 132 0.3404 7.063 0.491 179.3
64 260 0.1236 4.992 0.158 22.8
128 516 0.0455 3.534 0.033 21.5
n = 64: the worst tip error in rings of the distance r from the shoulder
r from-to (mm) points mean error (mm) worst error (mm)
20 - 40.0 3768 1.4981 4.992
40 - 80.0 15056 0.0300 0.158
80 - 120.0 25144 0.0052 0.014
120 - 160.0 35156 0.0049 0.021
160 - 170.0 10380 0.0117 0.041
170 - 175.0 5440 0.0331 0.101
175 - 178.0 3276 0.1205 0.358
178 - 180.5 2300 2.3163 4.988
The error falls fast with the table size (mean 2.5 mm at 8 entries, 0.12 mm at 64, 0.05 at 128) but it is not spread evenly. For n = 64 the points between 40 and 170 mm from the shoulder are accurate to 0.16 mm at worst, but the two ends are bad: 5 mm near the folded arm (r below 40) and 5 mm near the straight arm (r above 178). The reason is the shape of the function: acos has an infinite slope at ±1, exactly where the arm is folded or straight, so a table with even steps cannot follow it there, and these are the two places where a small angle error moves the tip most. A table is only as good as the region you promise to stay in; the table size is the price of how close to the edge you are willing to go.
What the tables cost on the Uno
The cost-test sketch has eight variants, one function each, fed from analogRead so the compiler cannot remove it, and printed as an integer so Serial’s float printing is in none of them (the lesson of Programming for Robotics with Arduino C++ 10). Variant 0 is the baseline.
variant flash (bytes) vs baseline RAM (bytes) vs baseline
0 baseline (nothing) 1960 - 188 -
1 ik: sqrtf and atan2f (the library) 4082 +2122 188 0
2 ik_lut: tables in flash 4552 +2592 188 0
3 fk: sinf and cosf 3412 +1452 188 0
4 fk_int: integer sine table 2548 +588 188 0
5 Trap::pos (one step) 4220 +2260 216 +28
6 Trap::plan 3548 +1588 188 0
7 two Servo objects (attach, write) 3592 +1632 232 +44
And, from avr-objdump (script count_arm.py), the step function of each variant: its size, its instructions, and the library routines it calls. These are the function itself; in variant 2 two helpers, table_interp and atan2_lut, were not inlined and are not counted in its 188 instructions:
And the sizes of the routines reached, from avr-nm (hexadecimal bytes):
$ avr-nm -S -C: symbol sizes in hex bytes (static code size, not run time)
-- variant 1 (ik) --
00000f5e 0000001c T __fp_mpack
00000cf8 0000004e T __fp_powser
00000d84 00000044 T __fp_split3
00000a0c 00000086 T atan2
00000ed6 0000008c T sqrt
-- variant 3 (fk) --
00000a80 00000056 T __fp_rempio2
00000af4 00000028 T __fp_sinus
0000095e 0000000a T cos
00000c48 00000010 T sin
-- variant 2 (ik_lut): the two helpers that are not inlined, and the tables --
000001c2 000000e6 t table_interp(unsigned int const*, unsigned char, float) [clone .constprop.15]
000002a8 00000150 t atan2_lut(float, float, unsigned int const*, unsigned char) [clone .constprop.13]
00000068 00000082 t ACOS_T
000000ea 00000082 t ATAN_T
The result is the opposite of what I expected. The lookup tables did not save flash: they cost 470 bytes more (+2592 against +2122). The library’s atan2 is only 134 bytes (0x86) and sqrt 140, so the routine the table replaces was small; the replacement is two helpers of 230 and 336 bytes plus 260 bytes of tables, and all the float multiplications and the division stay (the inverse kinematics needs them for the law of cosines whichever way the angles are found). Whether the tables are faster I cannot say: nothing was timed, and the idea that a table is faster than a long library routine is plausible and not shown here. What the numbers do show is that a table is not a free saving of space, and that the tables only make sense if the time matters and the flash is there.
The integer table is different. fk_int() takes whole degrees, which is all the servo can use anyway, looks the sine up in a 91-entry table (182 bytes, 0 to 90°; the other quadrants are folded back), and does everything in integers: 92 instructions and no float call at all, +588 bytes of flash against +1452 for fk() with sinf and cosf. When the answer is only needed to the servo’s resolution, the table with integer arithmetic is the cheap one: not because lookup is clever, but because it removes the floating-point library.
6. A pick-and-place cycle on the simulator
Now the pieces together. The shoulder is at the origin, the table surface at y = −40 mm, the object is at a pick point, the grip point is lowered to 2 mm above the table, and the arm carries the object to a place point. The cycle has seven legs: from home to above the pick, down to the pick, up, across to above the place, down, up, home. Each leg is a joint-space move of the previous section, commanded every 20 ms. The servo model is an assumption: it takes whole degrees (or 1 µs steps), follows the command with a straight ramp between updates, and has 0.8° of play: it does not move until the command has gone 0.4° past it. The tip is followed every millisecond.
// e_pick.cpp -- a pick-and-place cycle for the 2-link arm on the simulator (host build; the arm, the table, the speeds and the servo play are ASSUMED: no real arm was built or measured).
// Arm l1 = 100, l2 = 80 mm, shoulder at the origin, table surface at y = -40 mm. The grip point is lowered to y = -38 mm (2 mm above the table), travel height y = +20 mm.
// Sequence: home (110, 40) -> above pick -> pick -> above pick -> above place -> place -> above place -> home. Each leg is a move in JOINT space (both joints start and stop together, trapezoid 120 deg/s, 400 deg/s^2),
// commanded every 20 ms. The servos take whole degrees (write(int)) or 1 us steps (0.097 deg); each joint has 0.8 degree of play: it only moves after the command has moved 0.4 degree past it.
// The tip is followed every millisecond (the command between two updates is a straight line, as a servo's own ramp would be) and scored: time, the deepest the tip goes below the table, the error at the pick and place points, and how far a "straight down" leg wanders sideways.
#include <cstdio>
#include <cmath>
#include <vector>
#include "arm.h"
#include "sim.h"
static const float D2R = 3.14159265f / 180.0f, R2D = 180.0f / 3.14159265f;
struct Pt { float x, y; };
struct Leg { Pt to; bool is_down; };
struct Result { double total_s, deepest, err_pick, err_place, sideways; int hits; };
static Result run_cycle(const Arm& arm, float px, float qx, float step_deg, float grasp_y, bool verbose) {
const float TRAVEL = 20.0f, GRASP = grasp_y, TABLE = -40.0f, PLAY = 0.8f;
Leg legs[7] = {{{px, TRAVEL}, false}, {{px, GRASP}, true}, {{px, TRAVEL}, false}, {{qx, TRAVEL}, false}, {{qx, GRASP}, true}, {{qx, TRAVEL}, false}, {{110.0f, 40.0f}, false}};
Result r = {0, 0, 0, 0, 0, 0};
float j1 = 0, j2 = 0; ik(arm, 110.0f, 40.0f, true, j1, j2); // joint angles (rad) at home
float act1 = j1, act2 = j2; // where the joints really are (with play)
float prev_c1 = j1, prev_c2 = j2; // the last quantised commands
double clock = 0;
for (int li = 0; li < 7; ++li) {
float t1, t2;
if (!ik(arm, legs[li].to.x, legs[li].to.y, true, t1, t2)) { r.total_s = -1; return r; }
Trap a, b; plan_sync(a, b, (t1 - j1) * R2D, (t2 - j2) * R2D, 120.0f, 400.0f);
double leg_t = a.T > b.T ? a.T : b.T;
int updates = (int)std::ceil(leg_t / 0.02 - 1e-9);
double x_at_start = 0, x_sum = 0; float x_min = 1e9f, x_max = -1e9f;
float q1_prev = prev_c1, q2_prev = prev_c2;
for (int u = 1; u <= updates; ++u) {
double tt = u * 0.02; if (tt > leg_t) tt = leg_t;
float c1 = j1 + a.pos((float)tt) * D2R, c2 = j2 + b.pos((float)tt) * D2R;
float q1 = std::round(c1 * R2D / step_deg) * step_deg * D2R, q2 = std::round(c2 * R2D / step_deg) * step_deg * D2R;
double dt = tt - (u - 1) * 0.02; // length of this slice (the last one may be short)
int ms = (int)std::lround(dt * 1000.0);
for (int m = 1; m <= ms; ++m) {
float f = (float)m / (float)ms;
float cmd1 = q1_prev + (q1 - q1_prev) * f, cmd2 = q2_prev + (q2 - q2_prev) * f;
float h = 0.5f * PLAY * D2R;
if (cmd1 > act1 + h) act1 = cmd1 - h; else if (cmd1 < act1 - h) act1 = cmd1 + h;
if (cmd2 > act2 + h) act2 = cmd2 - h; else if (cmd2 < act2 - h) act2 = cmd2 + h;
float x, y; fk(arm, act1, act2, x, y);
if (y < TABLE) { r.hits++; if (TABLE - y > r.deepest) r.deepest = TABLE - y; }
if (legs[li].is_down) { if (x < x_min) x_min = x; if (x > x_max) x_max = x; }
}
q1_prev = q1; q2_prev = q2;
(void)x_at_start; (void)x_sum;
}
prev_c1 = q1_prev; prev_c2 = q2_prev;
float x, y; fk(arm, act1, act2, x, y);
double err = std::hypot(x - legs[li].to.x, y - legs[li].to.y);
if (li == 1) r.err_pick = err;
if (li == 4) r.err_place = err;
if (legs[li].is_down && x_max - x_min > r.sideways) r.sideways = x_max - x_min;
if (verbose) std::printf(" leg %d to (%6.1f, %6.1f) %.3f s %3d updates tip ends at (%7.2f, %7.2f), %.2f mm from the target\n", li + 1, legs[li].to.x, legs[li].to.y, leg_t, updates, x, y, err);
clock += updates * 0.02; r.total_s = clock;
j1 = t1; j2 = t2;
}
return r;
}
int main() {
const Arm arm = {100.0f, 80.0f};
std::printf("one cycle: pick at x = 120, place at x = 60 (servo step 1 degree)\n");
run_cycle(arm, 120.0f, 60.0f, 1.0f, -38.0f, true);
struct { const char* name; float step; } modes[2] = {{"whole degrees", 1.0f}, {"1 microsecond", 0.097f}};
const float grasps[2] = {-38.0f, -39.5f};
for (int g = 0; g < 2; ++g) {
std::printf("\n200 cycles, pick and place x drawn from 60..140 mm (at least 30 mm apart); table at y = -40, grip point lowered to y = %.1f (%.1f mm above the table)\n", grasps[g], grasps[g] + 40.0f);
std::printf(" servo step cycle time (s) mean / max tip below the table: cycles / deepest (mm) pick error mean / worst (mm) place error mean / worst (mm) sideways drift while lowering: mean / worst (mm)\n");
for (int m = 0; m < 2; ++m) {
Rng rng(4242u);
double tsum = 0, tmax = 0, deep = 0, pe = 0, pw = 0, qe = 0, qw = 0, sd = 0, sw = 0; int cycles = 0, hit_cycles = 0, done = 0;
while (done < 200) {
float px = 60.0f + 80.0f * (float)rng.uniform(), qx = 60.0f + 80.0f * (float)rng.uniform();
if (std::fabs(px - qx) < 30.0f) continue;
Result r = run_cycle(arm, px, qx, modes[m].step, grasps[g], false);
if (r.total_s < 0) continue;
++done; ++cycles; tsum += r.total_s; if (r.total_s > tmax) tmax = r.total_s;
if (r.hits) ++hit_cycles;
if (r.deepest > deep) deep = r.deepest;
pe += r.err_pick; if (r.err_pick > pw) pw = r.err_pick;
qe += r.err_place; if (r.err_place > qw) qw = r.err_place;
sd += r.sideways; if (r.sideways > sw) sw = r.sideways;
}
std::printf(" %-16s %12.2f / %-6.2f %18d / %-18.2f %18.2f / %-8.2f %19.2f / %-8.2f %27.2f / %-8.2f\n", modes[m].name, tsum / cycles, tmax, hit_cycles, deep, pe / cycles, pw, qe / cycles, qw, sd / cycles, sw);
}
}
return 0;
}
one cycle: pick at x = 120, place at x = 60 (servo step 1 degree)
leg 1 to ( 120.0, 20.0) 0.347 s 18 updates tip ends at ( 119.32, 19.50), 0.85 mm from the target
leg 2 to ( 120.0, -38.0) 0.534 s 27 updates tip ends at ( 119.82, -37.07), 0.95 mm from the target
leg 3 to ( 120.0, 20.0) 0.534 s 27 updates tip ends at ( 120.38, 18.61), 1.45 mm from the target
leg 4 to ( 60.0, 20.0) 0.676 s 34 updates tip ends at ( 60.23, 20.20), 0.31 mm from the target
leg 5 to ( 60.0, -38.0) 0.728 s 37 updates tip ends at ( 59.92, -37.65), 0.36 mm from the target
leg 6 to ( 60.0, 20.0) 0.728 s 37 updates tip ends at ( 60.23, 20.20), 0.31 mm from the target
leg 7 to ( 110.0, 40.0) 0.642 s 33 updates tip ends at ( 109.37, 39.37), 0.89 mm from the target
200 cycles, pick and place x drawn from 60..140 mm (at least 30 mm apart); table at y = -40, grip point lowered to y = -38.0 (2.0 mm above the table)
servo step cycle time (s) mean / max tip below the table: cycles / deepest (mm) pick error mean / worst (mm) place error mean / worst (mm) sideways drift while lowering: mean / worst (mm)
whole degrees 3.93 / 4.44 0 / 0.00 0.94 / 2.07 0.91 / 2.10 5.70 / 7.65
1 microsecond 3.93 / 4.44 0 / 0.00 0.70 / 0.81 0.70 / 0.79 5.17 / 6.46
200 cycles, pick and place x drawn from 60..140 mm (at least 30 mm apart); table at y = -40, grip point lowered to y = -39.5 (0.5 mm above the table)
servo step cycle time (s) mean / max tip below the table: cycles / deepest (mm) pick error mean / worst (mm) place error mean / worst (mm) sideways drift while lowering: mean / worst (mm)
whole degrees 3.96 / 4.44 3 / 0.34 0.92 / 1.90 0.91 / 1.89 5.95 / 8.01
1 microsecond 3.96 / 4.44 0 / 0.00 0.69 / 0.79 0.70 / 0.81 5.43 / 6.80
One cycle (pick at x = 120, place at x = 60) is seven legs of 0.35–0.73 s. Over 200 cycles with random pick and place points the commanded motion takes 3.9 s (4.4 s at worst), the same with either servo step; the gripper’s pauses are not counted. Three results matter.
Play, not the step, is the floor. With 1 µs steps the tip is still 0.70 mm from the target on average (0.8 mm at worst): the 0.8° of play of the model, which no finer command removes. Whole degrees add a worse error (0.94 mm mean, up to 2.1 mm) on top.
The margin above the table. With 2 mm of clearance nobody touches the table, though the error of whole degrees reaches 2.07 mm (the error happened to point sideways). At 0.5 mm of clearance, 3 cycles in 200 with whole degrees push the tip as much as 0.34 mm below the table, and none with microseconds. A clearance smaller than the largest error is not a clearance; on a real arm I would choose it from a measured error, not a simulated one.
Joint-space legs are not straight. Lowering the tip “straight down” at the pick moves it sideways by 5.2–5.7 mm on average and up to 6.5–8.0 mm in the worst cycle, because the two joints move together by their own proportions and the tip follows the curve that makes. For picking something up from a hole or between two others, that is a collision. Challenge 3 compares this with a straight-line move.
7. On the Uno
robot_ch11.ino runs the same cycle: seven legs of the table LEGS; for each leg ik_lut() gives the joint angles (refusing a point that is out of reach or that a servo cannot reach, with the zero positions below), plan_sync() sets up the two profiles, and a 20 ms control task writes writeMicroseconds with the interpolated angles; the gripper closes after leg 2 and opens after leg 5, with a 400 ms pause each time. The servo’s zero positions are assumptions that I chose so that every point of the cycle lies inside 0–180° of each servo (shoulder −60 to +120°, elbow −150 to +30°): the cycle uses 17–86° at the shoulder and −141 to −73° at the elbow, so an elbow servo centred at 90° (±90°) could not do the job. The scheduler is the one of Programming for Robotics with Arduino C++ 1.
// robot_ch11.ino -- Programming for Robotics with Arduino C++, chapter 11: a pick-and-place cycle for a 2-link arm on three hobby servos.
// Compile-checked for the Uno (arduino:avr:uno). NOT run on a board: no arm was built or attached. The link lengths, the servo zero positions, the gripper angles and the travel heights are ASSUMED:
// measure your own arm and change them. The inverse kinematics uses the lookup tables in flash (tables.h, made by e_gen.cpp); each leg is a synchronised trapezoid in joint space.
#include <Servo.h>
#include "scheduler.h"
#include "pins.h"
#include "tables.h"
const uint8_t PIN_SHOULDER = 9, PIN_ELBOW = 10, PIN_GRIP = 13; // the only free pins after the plan of Programming for Robotics with Arduino C++ 2: 13 gives up the LED
static_assert(pin_ok(PIN_SHOULDER, R_DIGITAL) && pin_ok(PIN_ELBOW, R_DIGITAL) && pin_ok(PIN_GRIP, R_DIGITAL), "servo pins must be free digital pins");
// The Servo library takes Timer1: analogWrite on pins 9 and 10 stops working (the motors of this robot are on 5 and 6, Timer0, so they are not affected).
const Arm ARM = {100.0f, 80.0f}; // ASSUMED link lengths in mm
const float SHOULDER_ZERO = 60.0f, ELBOW_ZERO = 150.0f; // ASSUMED: servo angle = joint angle in degrees + zero (shoulder 0..180 -> -60..+120 degrees, elbow -150..+30)
const float V_MAX = 120.0f, A_MAX = 400.0f; // ASSUMED deg/s and deg/s^2 the servos can follow
const float TRAVEL_Y = 20.0f, GRASP_Y = -38.0f, PICK_X = 120.0f, PLACE_X = 60.0f;
const int GRIP_OPEN = 40, GRIP_CLOSED = 110; // ASSUMED servo degrees
struct Wp { float x, y; };
static const Wp LEGS[7] = {{PICK_X, TRAVEL_Y}, {PICK_X, GRASP_Y}, {PICK_X, TRAVEL_Y}, {PLACE_X, TRAVEL_Y}, {PLACE_X, GRASP_Y}, {PLACE_X, TRAVEL_Y}, {110.0f, 40.0f}};
static Servo s_shoulder, s_elbow, s_grip;
static float cur1 = 0.0f, cur2 = 0.0f; // joint angles at the end of the last leg (degrees)
static float to1 = 0.0f, to2 = 0.0f;
static Trap tj1, tj2;
static uint8_t leg = 0;
static uint32_t leg_start = 0, dwell_until = 0;
static bool running = false, failed = false;
static Scheduler<2> sch;
static int deg_to_us(float servo_deg) { // the Servo library's own map: 0..180 degrees = 544..2400 us, to 1 us
if (servo_deg < 0.0f) servo_deg = 0.0f; else if (servo_deg > 180.0f) servo_deg = 180.0f;
return 544 + (int)(servo_deg * (1856.0f / 180.0f) + 0.5f);
}
static void write_joints(float d1, float d2) { s_shoulder.writeMicroseconds(deg_to_us(SHOULDER_ZERO + d1)); s_elbow.writeMicroseconds(deg_to_us(ELBOW_ZERO + d2)); }
static bool start_leg(uint8_t i, uint32_t now) {
float t1, t2;
if (!ik_lut(ARM, LEGS[i].x, LEGS[i].y, true, t1, t2, ACOS_T, ATAN_T, LUT_N)) return false; // out of reach: refuse, never guess
to1 = t1 * 57.29578f; to2 = t2 * 57.29578f;
float s1 = SHOULDER_ZERO + to1, s2 = ELBOW_ZERO + to2;
if (s1 < 0.0f || s1 > 180.0f || s2 < 0.0f || s2 > 180.0f) return false; // the servo cannot go there
plan_sync(tj1, tj2, to1 - cur1, to2 - cur2, V_MAX, A_MAX);
leg_start = now;
return true;
}
static void control_task(void*, uint32_t now) {
if (!running || failed) return;
if ((int32_t)(now - dwell_until) < 0) return; // waiting for the gripper
float t = (float)(now - leg_start) * 0.001f;
float T = tj1.T > tj2.T ? tj1.T : tj2.T;
if (t >= T) { // the leg is done: land exactly on its target, then the next
cur1 = to1; cur2 = to2; write_joints(cur1, cur2);
if (leg == 1) { s_grip.write(GRIP_CLOSED); dwell_until = now + 400; }
if (leg == 4) { s_grip.write(GRIP_OPEN); dwell_until = now + 400; }
if (++leg >= 7) { running = false; return; }
if (!start_leg(leg, now + (dwell_until > now ? 400 : 0))) { failed = true; }
return;
}
write_joints(cur1 + tj1.pos(t), cur2 + tj2.pos(t));
}
static void report_task(void*, uint32_t now) {
Serial.print(now); Serial.print(F(" ms leg ")); Serial.print(leg + 1); Serial.print(F(" joints ")); Serial.print(cur1, 1); Serial.print(' '); Serial.print(cur2, 1);
Serial.println(failed ? F(" FAILED: a leg is out of reach or out of the servos' range") : running ? F("") : F(" done"));
}
void setup() {
Serial.begin(115200);
s_shoulder.attach(PIN_SHOULDER); s_elbow.attach(PIN_ELBOW); s_grip.attach(PIN_GRIP);
s_grip.write(GRIP_OPEN);
float t1, t2;
ik_lut(ARM, 110.0f, 40.0f, true, t1, t2, ACOS_T, ATAN_T, LUT_N); // the home position
cur1 = t1 * 57.29578f; cur2 = t2 * 57.29578f; write_joints(cur1, cur2);
delay(1000); // let the arm reach home before the first move
running = start_leg(0, millis()); failed = !running;
sch.add(control_task, 0, 20);
sch.add(report_task, 0, 500);
}
void loop() { sch.run(millis()); }
It compiles for the Uno under --warnings all with no warning from the sketch to:
Sketch uses 10040 bytes (31%) of program storage space. Maximum is 32256 bytes.
Global variables use 437 bytes (21%) of dynamic memory, leaving 1611 bytes for local variables. Maximum is 2048 bytes.
That is 10,040 bytes of flash and 437 bytes of RAM. It was not run: there is no arm, the link lengths, zero positions, gripper angles and limits are guesses, and I never saw a servo move. The first thing to do on a real arm is to measure the two link lengths and the real range of each servo, then to move one joint at a time with writeMicroseconds at a small speed.
8. What the numbers can and cannot be trusted for
What they show. The shapes: the inverse kinematics is exact and refuses what it cannot reach; the tip error from a servo step is about the reach times the step, so whole degrees give millimetres and microseconds give a tenth of a millimetre; a trapezoid profile is exact and a synchronised pair of joints arrives together; whole-degree commands turn a slow move into stop-and-go; a lookup table is accurate in the middle of its range and poor at the ends where the function is steep; joint interpolation curves the tip’s path by several millimetres; the sizes of every variant on the Uno and the counts of instructions and library calls.
What they do not show. The arm is a simulation with link lengths, limits and play that I chose: a real servo has a speed limit and a torque limit that depend on its load and voltage, a backlash that is not a symmetric deadband, a pulse-to-angle map that differs from the library’s 544–2400, and it does not follow a command in a straight ramp. The Servo-library behaviour is read from source, not seen on a pin. No gravity, no payload, no gripper geometry, no collision except with the table. No time was measured: the Uno figures are bytes, instructions and calls, so “the table is faster” and “integers are faster” are expectations, not results. robot_ch11.ino was compiled, not run.
Challenge 1: The servo step for half a millimetre
Round both joint angles to steps from 2° down to 0.025° and measure the tip error over the working area (y ≥ −40 mm, 30 ≤ r ≤ 170 mm), overall and in three rings of the distance from the shoulder. Which is the coarsest step that places the tip within 0.5 mm everywhere, what is it in microseconds, and in which ring is the error worst?
Give ik_lut() an acos table and an atan table of different sizes (8, 16, 32, 64 and 128 entries each) and report the worst tip error over 40 ≤ r ≤ 170 mm for every pair. Which table decides the accuracy, what is the cheapest pair in flash that stays below 0.5 mm, and what does it save against two tables of 64?
For three legs of the cycle compare the joint-space move with a Cartesian move (a trapezoid along the straight line, inverse kinematics at every 20 ms step): how far the tip strays from the straight line, and how long the leg takes when the Cartesian move is run at the largest tip speed at which no joint exceeds 120°/s or 400°/s². When is the straight line worth the extra time?
Kinematics.x = l1 cos t1 + l2 cos(t1+t2), cos t2 = (x²+y²−l1²−l2²)/(2 l1 l2); outside [−1, 1] return false. Round trip within 0.00006 mm over 100,520 points; reachable ring r = 20–180 mm for 100 and 80 mm links.
Servo step. Tip error is about reach × step: whole degrees 0.63 mm mean, 2.07 worst; 1 µs (0.097°) 0.06 and 0.20; 0.5 µs tick 0.03 and 0.10. 0.1° meets 0.5 mm, 0.25° does not (0.52 mm).
The edge. Moving the tip outward at 50 mm/s takes 12–58°/s between 40 and 150 mm and 637 and 1,433°/s at 179.95 mm: keep waypoints away from the straight arm.
Servo library (read, not run). 544–2400 µs for 0–180°; write(int) is whole degrees; Timer1 at 0.5 µs per tick; 20 ms frame, servos pulsed one after another, 12 per timer; attach puts Timer1 in normal mode, so I expect analogWrite on pins 9 and 10 to stop (not run).
Trapezoid. Triangle if d < vmax²/amax (36° for 120 and 400); synchronise by scaling the shorter joint’s limits by the ratio of distances: 60° and 15° both finish at 0.800 s. Whole-degree commands at a slow speed give stop-and-go: 47 of 77 updates still, 1° jumps at 50°/s for a 20°/s move.
Lookup tables. n = 64: 0.16 mm worst in 40–170 mm, about 5 mm at both ends (acos is steep at ±1). They did not save flash: ik +2122 bytes, ik_lut +2592 (260 bytes of tables); speed not measured. The integer sine table: fk_int +588 against +1452 for the float fk.
Pick and place (simulated, play 0.8°). 3.9 s of commanded motion per cycle; tip error 0.70 mm with microsecond steps (play is the floor), 0.94 mm mean and 2.1 mm worst with whole degrees; a joint-space “straight down” drifts 5–8 mm sideways.
Budget.robot_ch11.ino: 10,040 bytes flash (31 %), 437 bytes RAM (21 %), compiled, not run. Two Servo objects cost +1632 flash and +44 RAM; three servos use pins 9, 10 and 13 (the LED).
Not run: anything on a board; any real arm or servo; the speed of a table against a library routine, or of integers against floats.
Next: Programming for Robotics with Arduino C++ 12, Testing, Safety and Where to Go Next
Programming for Robotics with Arduino C++ 12 (planned; not yet written) closes the course: testing robot code on the PC before it touches hardware, the safety rules a robot that moves must follow (limits, watchdogs, an emergency stop that does not depend on the code that failed), a review of what the course measured and what it only compiled, and where to go next.