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
delay() with non-blocking millis() timingB90, E45, HOME, POSE n)struct arrays from Lesson 9.5The 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.
Same circuit, drawn as a pin map:
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.
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
} 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.
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.
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);
}
}
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.
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;)
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();
} 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.
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).
B60, E120, HOME, POSE 1Use a separate 5V supply for servos (shared ground), and avoid long loose jumper wires
The servo is drawing too much current from Arduino 5Vβuse external 5V for servos
Reverse the angle mapping in code or re-mount the servo horn after centering at 90Β°
Check the signal pin number, ensure servo ground is connected, and verify power polarity
Check the baud rate (9600), set the line ending to Newline, and confirm the command starts with B, E, HOME, or POSE
A delay() sneaked back into the loop β every wait must use the millis() pattern instead
Before moving on, make sure your smart servo controller works:
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.