Lesson 14: Adding the Forearm

A third servo, a new problem: two stick axes, three joints

๐Ÿฆพ Elbow servo joins the arm โ€” and the button becomes a control-pair switch

๐ŸŽฏ Learning Objectives

By the end of this lesson, you will:

  • Mount and wire a third SG90 as the elbow/forearm joint
  • Solve the "3 joints, 2 axes" problem with a control mode
  • Toggle modes with an edge-detected button
  • Show three joint angles plus the active mode on the OLED

Key Concepts:

  • Control pairs โ€” one input device, selectable targets
  • A state variable as a simple mode machine
  • Why three servos finally demand external power
  • Mechanical chain: shoulder โ†’ upper arm โ†’ elbow โ†’ forearm โ†’ gripper

๐Ÿฆพ Section 1: Where the Forearm Fits

Our arm has grown one joint per lesson: base rotates everything, shoulder lifts the upper arm. Now we add the elbow โ€” an SG90 at the end of the upper arm that bends the forearm, the last link before the tool:

shoulder servo horn
        โ”‚
   upper arm (~85 mm)
        โ”‚
   elbow SG90  <-- NEW: drives the forearm
        โ”‚
     forearm
        โ”‚
   2-finger gripper  <-- mounts at the tip

About that gripper

The small two-finger gripper bolts onto the forearm's tip in this lesson โ€” mechanically it rides along, and that's the point: the elbow's whole job is to position whatever is at the end of the arm. Powering the gripper's own actuator comes next; for now it travels with the forearm as a visual proof that the end of the chain is where the real work happens.

๐Ÿ“Œ Section 2: Pin Map & Wiring

Complete robot-arm pin map

  • OLED SDA / SCL: A4 / A5 (I2C bus)
  • Joystick VRx / VRy / SW: A0 / A1 / D2
  • Mode button: A2 โ€” repurposed! Now toggles which joint the Y-axis drives
  • Buzzer (optional): pin 8
  • Base servo: pin 9
  • Shoulder servo: pin 10
  • Elbow servo: pin 11 โ€” new

โš ๏ธ Three servos = regulated 5V / 3A+ supply required

Two SG90s could get away with the Uno's 5V pin under light load. Three cannot โ€” stalled servo spikes will brown-out the Arduino (and corrupt I2C, garbling your OLED). Wire all servo power rails to a regulated 5V supply rated around 3A or more. That headroom is not optional โ€” the gripper's own servo joins us in Lesson 15, bringing the count to four, and each SG90 can pull ~650โ€“800 mA when it stalls. A random USB power bank may sag or cut out under those spikes; a bench or wall supply rated 3A+ will not. And connect grounds together: external GND and Arduino GND must join at one point or the signals float.

๐ŸŽฎ Section 3: Three Joints, Two Axes

The joystick gives us X and Y. The arm now has base, shoulder, and elbow. Real machines solve this all the time โ€” a radio-controlled excavator has more joints than sticks. The trick: the stick controls a PAIR of joints, and a button picks which pair.

mode = SHOULDER (default):        mode = ELBOW:
   X stick -> base servo             X stick -> base servo
   Y stick -> shoulder servo         Y stick -> elbow servo
   
   A2 button click = flip the mode

The base always gets X โ€” reaching around is the most-used motion. Y then drives whichever vertical joint is "armed". One boolean is the entire state machine:

bool elbowMode = false;   // false: Y -> shoulder   true: Y -> elbow

// Edge-detect the A2 button once per loop pass
int btnState = digitalRead(modeButton);
if (btnState == LOW && lastBtnState == HIGH) {
    elbowMode = !elbowMode;              // flip the control pair
}
lastBtnState = btnState;

// Y deflection goes to whichever servo is "armed"
if (elbowMode) {
    elbowAngle = constrain(elbowAngle + signOf(lastDY) * stepFor(lastDY),
                           MIN_ANGLE, MAX_ANGLE);
    elbowServo.write(elbowAngle);
} else {
    shoulderAngle = constrain(shoulderAngle + signOf(lastDY) * stepFor(lastDY),
                              MIN_ANGLE, MAX_ANGLE);
    shoulderServo.write(shoulderAngle);
}

๐Ÿ” Why this is safe (and clever)

The "disarmed" servo simply isn't written โ€” it holds its last angle. When you flip back, it waits where you left it. And the OLED finally earns its keep: the mode text on line 1 tells the pilot which joint is armed before they push the stick. This is exactly how real mode-select buttons work on industrial controls.

๐Ÿ“บ Section 4: Three Angles on One Screen

The OLED layout gets a third readout. Base and shoulder share a size-2 row (5 chars each, ~60 px); elbow gets the row below; the debug line squeezes into the last 8 pixels:

void updateDisplay() {
    display.clearDisplay();
    display.setTextColor(SSD1306_WHITE);

    // Title + armed pair (yellow band)
    display.setTextSize(1);
    display.setCursor(0, 0);
    display.print("ARM STATUS  ");
    display.print(elbowMode ? "BASE+ELBOW" : "BASE+SHLDR");

    // Row 1: base & shoulder
    display.setTextSize(2);
    display.setCursor(0, 16);
    display.print("B:");
    printAngle(baseAngle);
    display.setCursor(64, 16);
    display.print("S:");
    printAngle(shoulderAngle);

    // Row 2: elbow
    display.setCursor(0, 36);
    display.print("E:");
    printAngle(elbowAngle);

    // Footer: live stick deflection
    display.setTextSize(1);
    display.setCursor(0, 56);
    display.print("dX:");
    display.print(lastDX);
    display.print("  dY:");
    display.print(lastDY);

    display.display();
}

๐Ÿ’ก Layout check

y=0 title (8px) ยท y=16 row 1 (16px) ยท y=36 row 2 (16px, ends 52) ยท y=56 footer (8px, ends 64). Every pixel budgeted โ€” that's the discipline of pixel displays. If text overlaps, you did the math wrong, not the library.

๐Ÿงฉ Section 5: The Complete Sketch

Same architecture, one more servo, one more edge-detected button. Still no delay() in loop():

// ============================================================
// Lesson 14: Adding the Forearm (elbow servo + gripper mount)
//   X -> base (pin 9)        always
//   Y -> shoulder (pin 10)   in SHOULDER mode
//   Y -> elbow (pin 11)      in ELBOW mode
//   A2 button -> flip mode   SW click -> home all three
//   OLED -> B/S/E angles + armed pair
// ============================================================

#include <Servo.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

Servo baseServo;
Servo shoulderServo;
Servo elbowServo;

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_ADDR 0x3C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

// ---- Pins ----
const int joyX       = A0;
const int joyY       = A1;
const int joySW      = 2;
const int modeButton = A2;   // repurposed Lesson-11 button

// ---- Servo state ----
int baseAngle     = 90;
int shoulderAngle = 90;
int elbowAngle    = 90;
const int MIN_ANGLE = 20;
const int MAX_ANGLE = 160;

// ---- Control-pair mode ----
bool elbowMode = false;      // false: Y -> shoulder   true: Y -> elbow

// ---- Joystick calibration ----
int centerX = 512;
int centerY = 512;
const int deadZone = 25;
int lastDX = 0;
int lastDY = 0;

// ---- Independent timers ----
unsigned long lastStepTime    = 0;
unsigned long lastDisplayTime = 0;
const int stepInterval    = 15;
const int displayInterval = 250;
const int maxStep = 4;

int lastSWState  = HIGH;
int lastBtnState = HIGH;

int signOf(int v) {
    return (v > 0) - (v < 0);
}

int stepFor(int deflection) {
    int d = abs(deflection);
    if (d < deadZone) return 0;
    return map(d, deadZone, 512, 1, maxStep);
}

void calibrateJoystick() {
    long sumX = 0, sumY = 0;
    for (int i = 0; i < 50; i++) {
        sumX += analogRead(joyX);
        sumY += analogRead(joyY);
        delay(10);
    }
    centerX = sumX / 50;
    centerY = sumY / 50;
}

void printAngle(int n) {
    if (n < 100) display.print(" ");
    display.print(n);
}

void updateDisplay() {
    display.clearDisplay();
    display.setTextColor(SSD1306_WHITE);

    display.setTextSize(1);
    display.setCursor(0, 0);
    display.print("ARM STATUS  ");
    display.print(elbowMode ? "BASE+ELBOW" : "BASE+SHLDR");

    display.setTextSize(2);
    display.setCursor(0, 16);
    display.print("B:");
    printAngle(baseAngle);
    display.setCursor(64, 16);
    display.print("S:");
    printAngle(shoulderAngle);
    display.setCursor(0, 36);
    display.print("E:");
    printAngle(elbowAngle);

    display.setTextSize(1);
    display.setCursor(0, 56);
    display.print("dX:");
    display.print(lastDX);
    display.print("  dY:");
    display.print(lastDY);

    display.display();
}

void setup() {
    Serial.begin(9600);
    baseServo.attach(9);
    shoulderServo.attach(10);
    elbowServo.attach(11);
    pinMode(joySW, INPUT_PULLUP);
    pinMode(modeButton, INPUT_PULLUP);
    baseServo.write(baseAngle);
    shoulderServo.write(shoulderAngle);
    elbowServo.write(elbowAngle);

    if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
        Serial.println("OLED not found - check wiring/address");
        while (true);
    }
    display.clearDisplay();
    display.setTextColor(SSD1306_WHITE);
    display.setTextSize(1);
    display.setCursor(0, 20);
    display.println("Calibrating...");
    display.println("Hands off stick!");
    display.display();

    calibrateJoystick();
    updateDisplay();
}

void loop() {
    // Job 1: timed servo motion (every 15 ms)
    if (millis() - lastStepTime >= stepInterval) {
        lastStepTime = millis();
        lastDX = analogRead(joyX) - centerX;
        lastDY = analogRead(joyY) - centerY;

        // X always drives the base
        baseAngle = constrain(baseAngle + signOf(lastDX) * stepFor(lastDX),
                              MIN_ANGLE, MAX_ANGLE);
        baseServo.write(baseAngle);

        // Y drives whichever vertical joint is armed
        if (elbowMode) {
            elbowAngle = constrain(elbowAngle + signOf(lastDY) * stepFor(lastDY),
                                   MIN_ANGLE, MAX_ANGLE);
            elbowServo.write(elbowAngle);
        } else {
            shoulderAngle = constrain(shoulderAngle + signOf(lastDY) * stepFor(lastDY),
                                      MIN_ANGLE, MAX_ANGLE);
            shoulderServo.write(shoulderAngle);
        }
    }

    // Job 2: timed screen refresh (every 250 ms)
    if (millis() - lastDisplayTime >= displayInterval) {
        lastDisplayTime = millis();
        updateDisplay();
    }

    // Job 3: buttons (every pass)
    int swState = digitalRead(joySW);
    if (swState == LOW && lastSWState == HIGH) {
        baseAngle = shoulderAngle = elbowAngle = 90;   // home all
    }
    lastSWState = swState;

    int btnState = digitalRead(modeButton);
    if (btnState == LOW && lastBtnState == HIGH) {
        elbowMode = !elbowMode;                        // flip control pair
        updateDisplay();                               // instant feedback
    }
    lastBtnState = btnState;
}

๐Ÿ”ง Section 6: Tuning and Next Steps

OLED garbles when elbow moves

Almost always power, not code. Three servos on USB 5V will brown-out โ€” switch to the external supply and double-check shared ground.

Elbow runs the wrong direction

Flip its sign: elbowAngle - signOf(lastDY) * stepFor(lastDY). Mechanical mounting flips directions; code adapts, not hardware.

Forgot which mode you're in

That's why the mode lives on line 1 of the screen. Want more? Beep the optional buzzer on pin 8 when the mode flips.

Arm reaches its limits

The forearm adds reach โ€” and new ways to hit the table. Watch the real arm, then shrink MIN/MAX_ANGLE ranges per joint to fit your build.

๐Ÿ› ๏ธ Put It Together โ€” Challenges

  • Highlight the armed joint: on the OLED, draw a drawRect() box around whichever readout is armed โ€” B+S row vs E row โ€” instead of relying only on the mode text.
  • Three-way mode: make the A2 button cycle SHOULDER โ†’ ELBOW โ†’ BOTH (Y drives both at half step each). What state variable replaces the boolean?
  • Pose memory: store two 3-servo poses in arrays; SW click toggles between them instead of homing.
  • Gripper prep: if your gripper has its own servo, pin 5 is free โ€” design the control mode for 4 joints. This is the next lesson's puzzle.
Take Lesson 14 Quiz โ†’
โ† Previous: Lesson 13
Course Overview
Next: Lesson 15 โ†’