Lesson 18: Using Sliders to Control Servos


Written by Jonathan Sim

You can find this lesson and more in the Arduino IDE (File -> Examples -> Andee). If you are unable to find them, you will need to install the Andee Library for Arduino IDE.

Works on iOS and Android
In this lesson, I'll show you how to control servos with a slider!

We'll create 3 buttons. One to make it slowly turn left, the other to make it slowly turn right. And the third one to quickly turn to a user-specified position. We'll also create one display box to tell us about the servo's current position:



Top of the Code

#include <SPI.h>
#include <Andee.h>
#include <Servo.h> 

AndeeHelper displaybox;
AndeeHelper sliderPosition;

Servo theServo; // Declare a servo
int currentPosition; // Stores current position of servo (from 0 to 180)
const int servoPin = 2; // Servo connected to pin 2


void setup()
  Andee.begin();  // Setup communication between Annikken Andee and Arduino
  Andee.clear();  // Clear the screen of any previous displays
  currentPosition = 0; // Initialise position to 0
  theServo.attach(servoPin); // Tell Arduino which pin the servo is connected to
  theServo.write(currentPosition); // Set servo to position 0
  setInitialData(); // Define object types and their appearance


void setInitialData()
  displaybox.setType(DATA_OUT); // Sets object as a text input button
  displaybox.setTitle("Current Position");
  // Draw position slider
  sliderPosition.setType(SLIDER_IN); // Set object as a slider
  sliderPosition.setLocation(1, 0, FULL); // Sliders can only be full size
  sliderPosition.setTitle("Control Servo Position");
  sliderPosition.setSliderMinMax(0, 180);
  sliderPosition.setSliderNumIntervals(181); // Set as discrete slider
  sliderPosition.setSliderReportMode(ON_VALUE_CHANGE); // Update values as you're moving 


void loop()
  currentPosition = sliderPosition.getSliderValue(INT); // Use INT to retrieve integer value

  delay(100); // Always leave a short delay for Bluetooth communication
  // Do not use a delay less than 100. Arduino's built-in servo library 
  // isn't well-designed and will cause the Arduino to crash.
comments powered by Disqus