In this tutorial, you’ll learn how to write a simple sketch (program) for controlling servos with the Arduino Uno board. The code below includes the basics and has numerical values that can be changed to your liking. The parts listed below are needed for the project.
Table of Contents
ToggleParts
- Arduino IDE for programming;
- Arduino UNO;
- Arduino USB cable;
- Servos;
- Jumper wires;
The code
[sourcecode language=”cpp”]
/*
Arduino Servo Code
*/
#include <Servo.h>
Servo servoOne; // Define our Servo
void setup()
{
servoOne.attach(10); // servo on digital pin 10
}
void loop()
{
servoOne.write(45); // Turn Servo Left to 45 degrees
delay(1000); // Wait 1 second
servoOne.write(0); // Turn Servo Left to 0 degrees
delay(1000); // Wait 1 second
servoOne.write(90); // Turn Servo back to center position (90 degrees)
delay(1000); // Wait 1 second
servoOne.write(135); // Turn Servo Right to 135 degrees
delay(1000); // Wait 1 second
servoOne.write(180); // Turn Servo Right to 180 degrees
delay(1000); // Wait 1 second
servoOne.write(90); // Turn Servo back to center position (90 degrees)
delay(1000); // Wait 1 second
}[/sourcecode]
Adding more than one servo!
1. Define a second servo
[sourcecode language=”cpp”]
Servo servoTwo; // Define our Servo)
[/sourcecode]
2. Attach it
[sourcecode language=”cpp”]
servoTwo.attach(12); // servo on digital pin 12
[/sourcecode]
3. Add it void loop
[sourcecode language=”cpp”]
servoTwo.write(45);
delay(1000);
[/sourcecode]
Removing/Editing Delays
- Delete the “delay(1000); // Wait 1 second” in the code to remove any delays.
- Edit “1000” to any other number you want. These numbers are in milliseconds so 1000 equals one second.
Changing the degrees
- Change “45” to any angle you want in “servoOne.write(45); // Turn Servo Left to 45 degrees”