Servo tutorial (Part 2)

In this post we’re going to control an RC servo with an arduino the easiest, most stupid way possible.

This example is for demonstration purposes only. It is very unlikely that you can use this method in any project.

Parts list

  • Some sort of arduino compatible board (I use a nano v3)
  • A miniature RC servo
  • Some wires

Let’s connect the the arduino with the RC servo. The black/brown wire from the servo to GND, the red one to 5V and the yellow/orange to D9.

servo_nano_connection

First we’re going to use a sketch that is very similar to the “Blink” example:

int outPin = 9;                 // digital pin 9

void setup()
{
  pinMode(outPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(outPin, HIGH);   // sets the pin on
  delayMicroseconds(1500);      // waits for 1.5 ms
  digitalWrite(outPin, LOW);    // sets the pin off
  delay(19);                    // waits for 19 ms
}

We’re using the “delayMicroseconds” function because we need sub-millisecond precision. When we upload and run this sketch, it immediately instructs the servo to move to middle position. Then seemingly nothing happens but if you try to rotate the arm with your fingers, you’ll see it doesn’t let you do so.

So let’s try something else:

int outPin = 9;                 // digital pin 9
int t = 0;

void setup()
{
  pinMode(outPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(outPin, HIGH);   // sets the pin on
  delayMicroseconds(1000);
  if (t > 50) delayMicroseconds(500);
  if (t > 100) delayMicroseconds(500);
  if (t > 150) t = 0;

  digitalWrite(outPin, LOW);    // sets the pin off
  delay(19);                   // pauses for 19 ms
  t++;

}

This sketch alternates the servo arm every second between 3 positions. If we examine the servo pulse signal with an oscilloscope, we’ll see something similar:

DS1Z_QuickPrint3

What’s the problem with this method? The timing is fully done in the main loop with delays and this means the arduino can not do anything else in the meantime. So this method is only useful in a very simple project when predefined movements with simple logic is necessary. Of course there are more sophisticated methods to control an RC servo. I’ll discuss this in the next part.

First part of the series

Leave a Reply

Your email address will not be published. Required fields are marked *