Lesson 11: Smart Servo Control

Smooth non-blocking motion and serial commands on two SG90 servos

🦾 Everything you build today is exactly what the robot arm will run on β€” no printed parts needed yet

🎯 Learning Objectives

Lesson Goals:

  • β€’ Replace delay() with non-blocking millis() timing
  • β€’ Ramp two servos smoothly to target angles at the same time
  • β€’ Build a Serial Monitor command interface (B90, E45, HOME, POSE n)
  • β€’ Store preset poses using the struct arrays from Lesson 9.5

Skills Developed:

  • β€’ Timing patterns used in every real robot program
  • β€’ Serial input parsing and simple text commands
  • β€’ Coordinated motion and safe angle limits
  • β€’ Software that transfers straight onto the robot arm later

πŸ“¦ Section 1: Parts Inventory

Electronic Components:

  • β€’ Arduino Uno microcontroller
  • β€’ 2x SG90 micro servos (call them "base" and "elbow" β€” they stay loose on your desk)
  • β€’ Breadboard (or expansion board) + jumper wires
  • β€’ Push button (A2 to GND, INPUT_PULLUP)
  • β€’ Potentiometer (A0) for angle control
  • β€’ Buzzer (optional) for command feedback
  • β€’ USB cable (also used for the Serial Monitor commands)

Mechanical Parts:

  • β€’ None required this week! The servos can sit loose on the table
  • β€’ (Optional) Tape or poster tack to keep servo bodies from wandering
  • β€’ (Optional) Paperclip or pointer taped to a servo horn to make motion easier to see

The 3D printed arm parts are still being designed. When they arrive, this exact program becomes the arm's control software β€” that's why we label the servos "base" and "elbow" now.

πŸ“Œ Section 2: Standard Pin Map

Same pin map as always β€” this is the map the robot arm will use too

  • Button: A2 (to GND, INPUT_PULLUP)
  • Potentiometer: A0
  • Buzzer (optional): pin 8
  • Base servo signal: pin 9
  • Elbow servo signal: pin 10

Wiring Diagrams

Fritzing breadboard diagram: Arduino Uno wired to two SG90 servos (pins 9 and 10), a potentiometer on A0, a button on A2, and an optional buzzer on pin 8
Breadboard layout: servos on pins 9/10, pot on A0, button on A2, optional buzzer on pin 8

Same circuit, drawn as a pin map:

Smart Servo Control β€” Wiring Map ARDUINO UNO R3 DIGITAL I/O POWER ANALOG IN D8 D9 ~ D10 ~ 5V GND A0 A2 5V + Piezo buzzer (optional) SG90 BASE SG90 ELBOW 10kΩ potentiometer pushbutton (INPUT_PULLUP) + − SIG 5V GND SIG 5V GND WIPER pin 1 = 5V pin 3 = GND leg leg = GND 5V 5V 5V

Reading the diagram: every red 5V dot is the same power rail β€” connect them all together (a breadboard power rail is perfect for this). Every ⏚ ground symbol is the same ground rail β€” all grounds must connect together. With two servos running, feed that 5V rail from an external 5V supply if things get jittery, and always keep the supply's GND tied to the Arduino's GND.

⏱️ Section 3: Why delay() Breaks Robot Programs

Up to now, every servo move you wrote probably used delay() to pause between steps. That works for a single servo β€” but delay() literally freezes the entire chip. While it waits, the button can't be read, the second servo can't move, and serial commands are ignored. A robot arm that must move two joints smoothly can't afford to freeze.

The fix is the non-blocking timing pattern: instead of sleeping, we check a clock. millis() returns how many milliseconds have passed since the program started. We remember the last time we did work, and only do the next step when enough time has elapsed:

unsigned long lastStepTime = 0;
const int stepInterval = 15;   // ms between motion steps

void loop() {
    if (millis() - lastStepTime >= stepInterval) {
        lastStepTime = millis();
        // do ONE small step of work here
    }
    // the rest of loop() keeps running β€” buttons,
    // serial, second servo all stay responsive
}

πŸ’‘ The Microwave Analogy

delay(2000) is like standing in front of the microwave watching it count down β€” you can't do anything else. millis() is like glancing at the clock while you do other things, and checking the microwave when it's time. Same 2 seconds, but your Arduino stays useful the whole time.

🀏 Section 4: Smooth, Coordinated Motion

A jerky robot jumps straight to its target angle. A smooth robot steps toward the target one degree at a time. We keep two numbers per servo: its current angle and its target angle. On every timed step, each servo moves one degree closer β€” and because both servos step in the same tick, they move together even when their distances differ.

int baseAngle   = 90;   // where the servo is now
int elbowAngle  = 90;
int baseTarget  = 90;   // where we want it to go
int elbowTarget = 90;

int moveToward(int current, int target) {
    if (current < target) return current + 1;
    if (current > target) return current - 1;
    return current;   // already there
}

void loop() {
    if (millis() - lastStepTime >= stepInterval) {
        lastStepTime = millis();
        baseAngle  = moveToward(baseAngle,  baseTarget);
        elbowAngle = moveToward(elbowAngle, elbowTarget);
        baseServo.write(baseAngle);
        elbowServo.write(elbowAngle);
    }
    // ... inputs and serial commands handled below,
    // they only change the TARGETS
}

Notice the separation: inputs change targets, the timed step moves servos. That's the core architecture of nearly every robot program you'll ever write.

πŸ“Ÿ Section 5: Serial Command Interface

Now for the fun part: typing commands into Serial Monitor to drive the servos. Our mini language:

  • B120 β†’ set base target to 120Β°
  • E45 β†’ set elbow target to 45Β°
  • HOME β†’ both servos return to 90Β°
  • POSE 2 β†’ run preset pose #2 (next section)
void handleSerial() {
    if (Serial.available() == 0) return;   // nothing typed? do nothing

    String cmd = Serial.readStringUntil('
');
    cmd.trim();        // remove spaces and the newline
    cmd.toUpperCase(); // "b90" and "B90" both work

    if (cmd.startsWith("B")) {
        baseTarget = constrain(cmd.substring(1).toInt(), 20, 160);
        Serial.println("Base target: " + String(baseTarget));
    } else if (cmd.startsWith("E")) {
        elbowTarget = constrain(cmd.substring(1).toInt(), 20, 160);
        Serial.println("Elbow target: " + String(elbowTarget));
    } else if (cmd == "HOME") {
        baseTarget = 90;
        elbowTarget = 90;
        Serial.println("Going home");
    } else {
        Serial.println("Unknown command: " + cmd);
    }
}

⚠️ Serial Monitor Settings

Set the Serial Monitor to 9600 baud (matching Serial.begin(9600)) and line ending to "Newline" or "Both NL & CR" β€” readStringUntil('\n') needs that newline to know your command is finished.

🎯 Section 6: Preset Poses with Structs

In Lesson 9.5 you learned that a struct groups related values, and an array of structs stores a whole table of them. A robot pose is exactly that β€” a name plus an angle for each joint:

struct Pose {
    const char* name;
    int base;
    int elbow;
};

Pose poses[] = {
    {"HOME",  90, 90},
    {"READY", 90, 45},
    {"REACH", 45, 20}
};
const int numPoses = sizeof(poses) / sizeof(poses[0]);

// inside handleSerial():
} else if (cmd.startsWith("POSE")) {
    int i = cmd.substring(5).toInt();      // "POSE 2" -> 2
    if (i >= 0 && i < numPoses) {
        baseTarget  = poses[i].base;
        elbowTarget = poses[i].elbow;
        Serial.println("Pose: " + String(poses[i].name));
    }
}

Extension challenge: make the A2 button step through the pose list β€” each press advances to the next pose and plays a buzzer chirp. (Hint: poseIndex = (poseIndex + 1) % numPoses;)

🧩 Section 7: The Complete Sketch

Everything from this lesson in one program. Upload it, open Serial Monitor at 9600 baud, and try B60, E120, POSE 2, and HOME. Pressing the A2 button cycles through the pose list β€” even while a servo is still moving.

// ============================================================
// Lesson 11: Smart Servo Control
// Two SG90 servos (base pin 9, elbow pin 10) with:
//   - non-blocking millis() motion timing
//   - smooth 1-degree stepping toward target angles
//   - Serial Monitor commands: B<deg>, E<deg>, HOME, POSE <n>
//   - preset poses stored in a struct array
//   - A2 button cycles poses (with debounce + buzzer chirp)
// ============================================================

#include <Servo.h>

Servo baseServo;
Servo elbowServo;

// ---- Current angles and target angles ----
int baseAngle   = 90;   // where the servo is now
int elbowAngle  = 90;
int baseTarget  = 90;   // where we want it to go
int elbowTarget = 90;

// ---- Non-blocking motion timing ----
unsigned long lastStepTime = 0;
const int stepInterval = 15;   // ms between 1-degree steps

// ---- Preset poses (struct array from Lesson 9.5) ----
struct Pose {
    const char* name;
    int base;
    int elbow;
};

Pose poses[] = {
    {"HOME",  90, 90},   // pose 0
    {"READY", 90, 45},   // pose 1
    {"REACH", 45, 20}    // pose 2
};
const int numPoses = sizeof(poses) / sizeof(poses[0]);
int poseIndex = 0;

// ---- Button on A2 (INPUT_PULLUP) ----
const int buttonPin = A2;
int lastButtonState = HIGH;
unsigned long lastPressTime = 0;

// ---- Optional buzzer on pin 8 ----
const int buzzerPin = 8;

// ---- Step one servo one degree toward its target ----
int moveToward(int current, int target) {
    if (current < target) return current + 1;
    if (current > target) return current - 1;
    return current;
}

// ---- Load a pose's angles into the targets ----
void setPose(int i) {
    if (i >= 0 && i < numPoses) {
        poseIndex   = i;
        baseTarget  = poses[i].base;
        elbowTarget = poses[i].elbow;
        Serial.print("Pose ");
        Serial.print(i);
        Serial.print(": ");
        Serial.println(poses[i].name);
    } else {
        Serial.println("No such pose");
    }
}

// ---- Read and act on one Serial Monitor command ----
void handleSerial() {
    if (Serial.available() == 0) return;   // nothing typed? do nothing

    String cmd = Serial.readStringUntil('\n');
    cmd.trim();         // remove spaces and the newline
    cmd.toUpperCase();  // "b90" and "B90" both work

    if (cmd.startsWith("POSE")) {
        setPose(cmd.substring(5).toInt());     // "POSE 2" -> 2
    } else if (cmd.startsWith("B")) {
        baseTarget = constrain(cmd.substring(1).toInt(), 20, 160);
        Serial.print("Base target: ");
        Serial.println(baseTarget);
    } else if (cmd.startsWith("E")) {
        elbowTarget = constrain(cmd.substring(1).toInt(), 20, 160);
        Serial.print("Elbow target: ");
        Serial.println(elbowTarget);
    } else if (cmd == "HOME") {
        setPose(0);                            // pose 0 IS home
    } else {
        Serial.print("Unknown command: ");
        Serial.println(cmd);
    }
}

// ---- Button press -> next pose (with 50ms debounce) ----
void handleButton() {
    int state = digitalRead(buttonPin);
    if (state == LOW && lastButtonState == HIGH
        && millis() - lastPressTime > 50) {
        lastPressTime = millis();
        setPose((poseIndex + 1) % numPoses);
        tone(buzzerPin, 1000, 60);   // chirp - delete if no buzzer
    }
    lastButtonState = state;
}

void setup() {
    Serial.begin(9600);
    baseServo.attach(9);
    elbowServo.attach(10);
    pinMode(buttonPin, INPUT_PULLUP);
    pinMode(buzzerPin, OUTPUT);
    baseServo.write(baseAngle);
    elbowServo.write(elbowAngle);
    Serial.println("Smart Servo Control ready.");
    Serial.println("Commands: B<deg>  E<deg>  HOME  POSE <0-2>");
}

void loop() {
    // 1. Timed motion step (non-blocking)
    if (millis() - lastStepTime >= stepInterval) {
        lastStepTime = millis();
        baseAngle  = moveToward(baseAngle,  baseTarget);
        elbowAngle = moveToward(elbowAngle, elbowTarget);
        baseServo.write(baseAngle);
        elbowServo.write(elbowAngle);
    }

    // 2. Inputs - they only change the TARGETS
    handleSerial();
    handleButton();
}

πŸ” Notice the structure

loop() does three quick things every pass: a timed motion step, a serial check, a button check. None of them block β€” that's why you can type HOME mid-move and it responds instantly. Every input only writes a target; the timed step does the actual moving.

πŸ”Œ Wiring and Connections

⚠️ Safety First!

Always disconnect power before making any connections. SG90 servos can draw bursts of current. If a servo jitters or resets your Arduino, consider powering the servos from a separate 5V source (and connect grounds).

Power Connections

  • β€’ Start with a single servo powered from Arduino 5V (test)
  • β€’ If the Arduino resets or the servo jitters, use an external 5V supply for servos
  • β€’ Always connect all grounds together (Arduino GND ↔ servo power supply GND)
  • β€’ Verify voltage levels before powering on

Signal Connections

  • β€’ Base servo signal β†’ pin 9
  • β€’ Elbow servo signal β†’ pin 10
  • β€’ Button β†’ A2 to GND (INPUT_PULLUP)
  • β€’ Potentiometer wiper β†’ A0 (other pins to 5V and GND)
  • β€’ (Optional) Buzzer β†’ pin 8 to GND

πŸ§ͺ Testing and Troubleshooting

Initial Testing Checklist

  • βœ… Visual inspection of all servo wires (signal/power/ground)
  • βœ… Test each servo individually with the Lesson 10 β€œbasic servo control” sketch
  • βœ… Serial Monitor set to 9600 baud with Newline line-ending
  • βœ… Try commands in order: B60, E120, HOME, POSE 1
  • βœ… Confirm the button still responds while a servo is mid-move (that proves your timing is non-blocking)

Common Issues and Solutions

Problem: Servo jitters

Use a separate 5V supply for servos (shared ground), and avoid long loose jumper wires

Problem: Arduino resets when servo moves

The servo is drawing too much current from Arduino 5Vβ€”use external 5V for servos

Problem: Servo moves in the wrong direction

Reverse the angle mapping in code or re-mount the servo horn after centering at 90Β°

Problem: Servo doesn’t move at all

Check the signal pin number, ensure servo ground is connected, and verify power polarity

Problem: Serial commands are ignored

Check the baud rate (9600), set the line ending to Newline, and confirm the command starts with B, E, HOME, or POSE

Problem: Button stops working while servo moves

A delay() sneaked back into the loop β€” every wait must use the millis() pattern instead

πŸ“ Assessment & Next Steps

Lesson 11 Verification

Before moving on, make sure your smart servo controller works:

  • βœ… Both servos ramp smoothly to targets (no jumps, no delay() anywhere)
  • πŸ“Ÿ Serial commands B, E, HOME, and POSE all work from Serial Monitor
  • πŸ”˜ Button stays responsive while servos are mid-move
  • ⚑ Power is stable (no resets during movement)
  • πŸ›‘οΈ Angles are clamped to safe limits (20°–160Β°)

🎯 Where This Leads

Next week we switch gears to the miniAuto car β€” but keep this sketch. The millis() timing pattern shows up everywhere in robotics, and when the 3D printed arm parts are ready, this program becomes the arm's control software almost unchanged: the poses you typed today become the poses the arm strikes.

Take Lesson 11 Quiz β†’
← Previous: Lesson 10
Course Overview
Next: Lesson 12 β†’