Servo sweep on an Arduino Uno
A micro servo on pin 9 jumps to 0, 90 and 180 degrees, then sweeps slowly back, with every angle on the serial monitor. The whole build, an Arduino Uno and 1 more part, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Servo sweep: the horn swings to 0, 90 and 180 degrees, then sweeps back.
//
// servo brown (GND) -> GND
// servo red (VCC) -> 5V
// servo orange (PWM) -> pin 9
//
// A hobby servo turns to an angle and holds it. It reads the angle from the
// width of a pulse sent fifty times a second: about 0.5 ms is one end, about
// 2.4 ms the other. The Servo library sends that pulse for you; write(angle)
// only changes how wide it is.
//
// The horn needs time to get there. This one moves about 60 degrees in a
// tenth of a second, so each jump waits a second before the next.
#include <Servo.h>
Servo horn;
void moveTo(int angle) {
horn.write(angle);
Serial.print("angle ");
Serial.println(angle);
}
void setup() {
horn.attach(9);
Serial.begin(9600);
Serial.println("Mokxi Uno: servo sweep");
}
void loop() {
moveTo(0);
delay(1000);
moveTo(90);
delay(1000);
moveTo(180);
delay(1000);
// A slow sweep back, one degree at a time.
for (int angle = 180; angle >= 0; angle--) {
horn.write(angle);
delay(10);
}
Serial.println("swept back to 0");
delay(1000);
}
Parts list
3 parts, plus the jumper wires. Every one is in the editor's parts bin.
- 1 × Arduino Uno R3
- 1 × Half breadboard
- 1 × Hobby servo
How it is wired
3 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Ground: Arduino Uno R3 pin GND; Hobby servo pin GND
- Arduino Uno R3 pin 9; Hobby servo pin PWM
- Arduino Uno R3 pin 5V; Hobby servo pin VCC
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.