Posts about... All (17) Android (2) Hooking Up Parts (10) Game Controllers (3) Robots (2)

How to Hook Up > Servos

A Servo, short for “servomechanism”, can rotate 180 or continuous 360 (depending on the type). Servos consist of a motor & a potentiometer and can easily be hooked up to an Arduino. This post details how.

Parts

Steps

  1. Typical (hobby) servos have 3 wires with a female header at the end. Insert a jumper wire into each of the header pins.
  2. Hook the RED wire up to +5V on the Arduino and hook up the BLACK wire to GROUND on the Arduino.
  3. The YELLOW wire is for data. Hook it up to a Digital Pin (8) on the Arduino.
  4. servo

  5. The servo library included in the Arduino IDE makes controlling servos very simple. Just include the servo library header file, declare a Servo object, attach your servo to a pin in the setup, then call the ‘write’ method on your servo object in order to change the servo’s position (rotation) Note: Remember to delay for at least 15ms after calling the ‘write’ method to give the servo time to move.
  6. Connect the Arduino to your computer with a USB cable (A to B) and upload the code below. Or, just simply go to File > Examples > Servo > Sweep in the Arduino IDE (same as below).

Code

#include <Servo.h>

Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created

int pos = 0; // variable to store the servo position

void setup()
{
myservo.attach(8); // 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 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}

A Step Further

If you’ve read my previous post, Hack a Nintendo (NES) Controller, you can now combine your knowledge to control servos with a NES controller. See the video below from my YouTube channel.

Code From Video

#include <NESpad.h>
#include <Servo.h>

NESpad nintendo = NESpad(2,3,4);
Servo myServo;
Servo otherServo;

byte state = 0;
int pos = 1; // myServo
int val = 1; // otherServo

void setup() {
myServo.attach(9);
otherServo.attach(10);
Serial.begin(9600);
}

void loop() {

delay(5);

state = nintendo.buttons();

// Left
if (state & NES_LEFT){
if(pos > 1){
pos = pos - 10;
myServo.write(pos);
delay(15);
Serial.println(pos);
}
}

//Right
if (state & NES_RIGHT){
if(pos < 179){
pos = pos + 10;
myServo.write(pos);
delay(15);
Serial.println(pos);
}
}

//B
if (state & NES_B){
if(val > 1){
val = val - 10;
otherServo.write(val);
delay(15);
Serial.println(val);
}

}

// A
if (state & NES_A){
if(val < 179){
val = val + 10;
otherServo.write(val);
delay(15);
Serial.println(val);
}
}

}