Sub topic 6
Smooth servo sweeps without delay()
This chapter assumes you can upload sketches, write functions and loops in Arduino C++, and have a servo wired to an external supply with a shared ground. You should also know how Servo.write() sets an angle. Here you will replace blocking delay() sweeps with a timer built on millis(). The servo then moves smoothly and the rest of your sketch keeps running.
Why delay() gets in the way
The simplest servo sweep steps the angle one degree at a time and calls delay(15) between steps.
#include <Servo.h>
Servo myServo;
const int SERVO_PIN = 9;
void setup() {
myServo.attach(SERVO_PIN);
}
void loop() {
for (int angle = 10; angle <= 170; angle++) {
myServo.write(angle);
delay(15);
}
for (int angle = 170; angle >= 10; angle--) {
myServo.write(angle);
delay(15);
}
}This works, and the motion looks smooth. The sweep stays between 10 and 170 degrees instead of 0 and 180, which keeps the servo away from its mechanical end stops and avoids straining the gears.
The problem is that delay() halts the sketch. A full sweep takes about 161 steps × 15 ms ≈ 2.4 seconds in each direction. During that time the Arduino cannot:
- read a button or sensor,
- update a display,
- run a second servo on a different schedule,
- respond to serial commands.
If a button is pressed while the sketch sits inside delay(15), you may miss it entirely. The sketch only looks at the button once per step, and only if you put the check inside the loops. Adding more tasks makes the code tangled, because every task must be squeezed into every for loop.
The idea: ask "is it time yet?"
Instead of waiting, let loop() run as fast as it can. On each pass, ask whether enough time has passed since the last servo step. If so, take one step. If not, skip the servo and move on.
The Arduino keeps a running clock. millis() returns the number of milliseconds since the board started, as an unsigned long. You store the time of the last step and compare it to the current time.
flowchart TDThat placeholder is not used. The real diagram is below.
The non-blocking sketch
#include <Servo.h>
Servo servo;
const int SERVO_PIN = 9;
const int MIN_ANGLE = 10;
const int MAX_ANGLE = 170;
const unsigned long STEP_MS = 15;
int angle = MIN_ANGLE;
int step = 1;
unsigned long lastStep = 0;
void setup() {
servo.attach(SERVO_PIN);
servo.write(angle);
}
void loop() {
unsigned long now = millis();
if (now - lastStep >= STEP_MS) {
lastStep = now;
angle += step;
if (angle >= MAX_ANGLE || angle <= MIN_ANGLE) {
step = -step;
}
servo.write(angle);
}
// Other work can run here on every pass through loop().
}How it works
angleholds the current position andstepholds the direction:+1moves up,-1moves down.lastSteprecords when the servo was last moved.now - lastStep >= STEP_MSis true once at least 15 ms have passed.- When
anglereaches either limit,step = -stepflips the direction. On the next step the angle moves back inside the range. servo.write(angle)runs only inside theif, so the servo gets a new target about every 15 ms.
The sweep speed is set by two numbers: STEP_MS and the size of step. A shorter interval or a larger step makes the servo move faster. Roughly, the speed in degrees per second is abs(step) × 1000 / STEP_MS. With the values above that is about 67 degrees per second.
Why subtraction matters
Write the comparison as now - lastStep >= STEP_MS. Do not write now >= lastStep + STEP_MS.
millis() counts up as an unsigned long (32 bits) and wraps back to zero after about 49.7 days. Unsigned subtraction handles the wrap correctly. If now has wrapped to a small number and lastStep is a large one, now - lastStep still produces the correct elapsed time, because unsigned arithmetic wraps modulo 2^32. The addition form breaks at the wrap, because lastStep + STEP_MS can overflow and make the test true or false at the wrong moment.
Keep every variable in this calculation unsigned long. Storing lastStep in an int truncates it to 16 bits on an Uno and the timing fails after about 32 seconds.
Edge cases and gotchas
The servo cannot move faster than it can physically move
If you set STEP_MS to 1 and step to 5, you are commanding the angle to change faster than a hobby servo can follow. It lags behind the command, then catches up in jerks. Typical hobby servos need roughly 100 to 200 ms to travel 60 degrees. Treat that as an upper limit on the speed you can request.
Your other code must not block either
The technique only helps if the rest of loop() is also quick. A delay(500) anywhere in your other code freezes the servo again. The same applies to pulseIn() with a long timeout, to blocking serial reads, and to some library calls that wait for a device. The servo is only as smooth as your slowest pass through loop().
You can see this by timing a pass. Passes much longer than STEP_MS mean the servo takes bigger, rougher jumps than intended, because it takes at most one step per pass.
Catching up after a slow pass
The sketch above takes one step per pass even if several intervals have elapsed. That keeps motion gentle but makes the sweep run slower than planned after a long pause. If you prefer a fixed average speed, take several steps in a row:
while (now - lastStep >= STEP_MS) {
lastStep += STEP_MS;
// advance angle by one step here
}Using lastStep += STEP_MS instead of lastStep = now also removes cumulative drift. With lastStep = now, each step is late by however long the loop took to notice, and these small delays add up. In most servo sweeps the drift does not matter, but it matters for anything that must keep time, such as a metronome.
Writing the same angle repeatedly
Calling servo.write() with an unchanged angle is harmless. The library keeps sending pulses every 20 ms in the background regardless of how often you call write(). This is why a servo holds position without any code from you. It also means that calling write() more often than every 20 ms gains nothing, since the servo only reads a new pulse once per frame.
Timer conflicts
On AVR boards such as the Uno, the Servo library uses Timer1. This disables analogWrite() (PWM) on pins 9 and 10. Move any PWM motor control to other PWM pins such as 3, 5, 6, or 11. Check your board's documentation, because other boards use different timers.
Moving to a target instead of sweeping
A sweep bounces between two limits. Often you want to go from the current position to a chosen target, then stop. Replace the direction logic with a comparison against a target:
#include <Servo.h>
Servo servo;
const int SERVO_PIN = 9;
const unsigned long STEP_MS = 20;
int angle = 90;
int target = 90;
unsigned long lastStep = 0;
void setup() {
Serial.begin(9600);
servo.attach(SERVO_PIN);
servo.write(angle);
}
void loop() {
if (Serial.available() > 0) {
int value = Serial.parseInt();
if (value >= 10 && value <= 170) {
target = value;
}
}
unsigned long now = millis();
if (now - lastStep >= STEP_MS && angle != target) {
lastStep = now;
if (angle < target) {
angle++;
} else {
angle--;
}
servo.write(angle);
}
}Open the Serial Monitor, set line ending to "No line ending", and type a number from 10 to 170. The servo glides to that angle at one degree per 20 ms while the sketch still listens for new commands. You can change the target mid-move and the servo reverses smoothly. This is the pattern for joystick control, remote commands, and sensor-driven positioning.
Because the sketch never blocks, a new target takes effect on the next pass. With delay()-based motion you would have to wait until the whole move finished.
The Serial.parseInt() call waits up to one second for more digits by default, which can briefly stall the loop when it returns without a number. For a servo project this is acceptable. For tighter timing, call Serial.setTimeout(10) in setup() to shorten the wait.
Comparing the approaches
| Approach | Servo smoothness | Other tasks run during motion | Code complexity |
|---|---|---|---|
| `delay()` in a `for` loop | Smooth | No, they wait | Lowest |
| `millis()` timer, one step per pass | Smooth if `loop()` is fast | Yes | Low |
| `millis()` with catch-up `while` | Smooth, keeps average speed | Yes, but a slow pass causes a burst | Medium |
| Easing curve (changing step size) | Smoothest start and stop | Yes | Higher |
Easing for softer starts and stops
A constant step size makes the servo start and stop abruptly, which can shake a lightweight arm. You can vary the speed by changing the delay between steps or by computing the angle from a curve. One simple way is to move a fraction of the remaining distance each interval:
#include <Servo.h>
Servo servo;
const int SERVO_PIN = 9;
const unsigned long STEP_MS = 20;
float position = 90.0;
float target = 90.0;
unsigned long lastStep = 0;
unsigned long lastTargetChange = 0;
void setup() {
servo.attach(SERVO_PIN);
servo.write((int)position);
}
void loop() {
unsigned long now = millis();
if (now - lastTargetChange >= 3000) {
lastTargetChange = now;
target = (target < 90.0) ? 160.0 : 20.0;
}
if (now - lastStep >= STEP_MS) {
lastStep = now;
position += (target - position) * 0.1;
servo.write((int)(position + 0.5));
}
}Each step covers 10 percent of the remaining distance. The servo moves fast at first and slows as it nears the target, giving a soft landing. The target flips between 20 and 160 degrees every three seconds. Because the move shrinks geometrically it never reaches the target exactly, but rounding to the nearest integer angle makes it settle within a degree or two. A float is used here because integer math would stall once the remaining distance gets small.
For finer resolution, writeMicroseconds() accepts pulse widths directly, typically 1000 to 2000 µs, and avoids the whole-degree rounding of write().
Summary of the pattern
- Store the time of the last action in an
unsigned long. - Each pass, compute
now - lastand compare it to the interval. - When the interval has passed, update the time, do one small unit of work, and write the servo.
- Keep every other part of
loop()short and non-blocking.
Exercises
Exercise
A student writes if (millis() >= lastStep + STEP_MS) and the servo freezes after the board has run for about 49 days. What is wrong, and how should the test be written?
Show answer
millis() wraps to zero after about 49.7 days, and the sum lastStep + STEPMS can overflow, so the comparison gives the wrong result near the wrap. Use unsigned subtraction instead: if (millis() - lastStep >= STEPMS), with lastStep declared as unsigned long.
Exercise
The non-blocking sweep uses STEP_MS = 15 and step = 1. What values would sweep at about 200 degrees per second, and what limit should you check before using them?
Show answer
Speed is abs(step) × 1000 / STEPMS. With STEPMS = 20 and step = 4 the speed is 4 × 1000 / 20 = 200 degrees per second. Check that the servo can physically follow that speed. Typical hobby servos need roughly 100 to 200 ms to move 60 degrees, so 200 degrees per second is near their limit, and larger steps look jerky.
Exercise
Add a push button on pin 2 (using INPUT_PULLUP) to the non-blocking sweep so that pressing it reverses direction at any time, without waiting for an end of travel. Which lines of the sketch change?
Show answer
Add pinMode(2, INPUT_PULLUP); in setup(). In loop(), outside the timed if block, read digitalRead(2). When it reads LOW and was HIGH on the previous pass, execute step = -step; and remember the new button state. Because loop() never blocks, the press is seen on the next pass. A simple edge check (comparing to a stored previous state) prevents the direction from flipping on every pass while the button is held.