Control a servo

Once more time for a POC. Well, a lot of people have proven it works… but I just want to see it working with my own eyes: controlling a servo via Arduino. Final goal: use the servo to move parts of analog cockpit gauges (e.g. attitude indicator).

A servo typically has three wires:

  • red: power (+)
  • black: ground (-)
  • Yellow/white: signal

For testing, I’ll be using an old Multiplex Nano-S servo, which accepts a voltage between 4.8V and 6V.

Arduino code:

/*
   Center the servo, afterwards sweep from right to left (and back) in a loop accross the entire range of the servo.

   The circuit:
   - Servo signal wire (yellow) to pin 3
   - Servo power to Arduino 5V (servo requires 4.8-6V)
   - Servo ground to Arduino ground

   Created 2017/09/09
   By Maarten Van Damme
   Modified
   By Maarten Van Damme

   http://projects.familievandamme.be

   Based on: http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo s1; //create servo object to control a servo
int pos = 0; //variable to store the servo position
int sleepTimeBetweenSteps = 50;
int sleepTimeBetweenCycles= 1000;

void setup() {
  s1.attach(3); //Determine signal pin
  firstRun(); 
}

void firstRun()
{
  s1.write(90); //Initialize position to center position
  delay(sleepTimeBetweenCycles);

  //First cycle needs to start from the center position.
  for (pos = 90; pos >= 0; pos -= 1)
  {
    s1.write(pos); //Move to position expressed in degrees.
    delay(sleepTimeBetweenSteps);
  }
  delay(sleepTimeBetweenCycles);
}

void loop() {
  //From 0 to 180
  for (pos = 0; pos <= 180; pos += 1)
  {
    // in steps of 1 degree
    s1.write(pos);
    delay(sleepTimeBetweenSteps);
  }
  delay(1000);
  //From 180 to 0
  for (pos = 180; pos >= 0; pos -= 1) {
    s1.write(pos);
    delay(sleepTimeBetweenSteps);
  }
  delay(sleepTimeBetweenCycles);
}

Conclusion: seems to be working BUT the servo I was using had a resolution which might be too low for my purpose. As a result, the servo movements are not very smooth (which could be an issue to have a realistic cockpit gauge).

Caution: don’t connect bigger servo’s directly to the Arduino power. Use instead a seperate power supply and share ground.

Sources:

  • https://www.arduino.cc/en/Reference/Servo
    • https://www.arduino.cc/en/Tutorial/Sweep
  • https://www.youtube.com/watch?v=fE4m7TyLd8M

1 comment

  1. Riani says:

    great post, thank you

Leave a Reply

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