KevsRobots Learning Platform
By , Minute
In this lesson you will learn how to control a servo using an Arduino.
Before you begin, you’ll need to make sure you have a couple of things before you start this lesson:
New Sketch button/* Sweep
by BARRAGAN <http://barraganstudio.com>
This example code is in the public domain.
modified 8 Nov 2013
by Scott Fitzgerald
https://www.arduino.cc/en/Tutorial/LibraryExamples/Sweep
*/
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15 ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15 ms for the servo to reach the position
}
}
An SG90 servo has three wires:
| Servo wire | Connect to |
|---|---|
| Brown (ground) | GND |
| Red (power) | 5V |
| Orange (signal) | D9 |
#include <Servo.h> loads the Arduino’s built-in servo library.myservo.attach(9) tells the library the servo’s signal wire is on pin 9.myservo.write(pos) moves the servo to an angle between 0 and 180 degrees.for loops step the angle up from 0 to 180, then back down again, one degree every 15 milliseconds, so the servo sweeps smoothly back and forth.delay(15) to delay(5). What happens to the sweep?Quick quiz 1 of 2
What range of angles can you send to an SG90 servo with myservo.write()?
Quick quiz 2 of 2
What does the orange wire on an SG90 do?
You can use the arrows ← → on your keyboard to navigate between lessons.
Comments