Exercise 2 - Servo motors and the 'if' statement

The Circuit

  • Luckily there is a built in library for dealing with servos, look in the examples to find the 'Knob' and 'Sweep' sketches, try them out if you like!
  • For additional information on servos there is a good Adafruit tutorial here
  • Follow the instructions in the code below:

/* This sketch shows how to use an if statement to check multiple parameters,
 * it will make a servo turn with the button on pin 6, 
 * but only a tiny bit before it will need a reset! 
 * See if you can add another button and another 'if' statement to get the 
 * servo to turn one way with one button and another with the other.
 * Look at the Arduino site reference page and the description of
 *  the 'if...else' statement under the 'Structure' section. You may need
 *  its help with the exercise!
 *  https://www.arduino.cc/en/Reference/HomePage
 *  You will need to add things to the declarations, the setup AND the main loop.
 *  Everything you need is already there, you just need to do some duplicating
 *  and name changing. 
 * Luke Woodbury 31 March 2016

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int pos = 90;    // variable to store the servo position
int lastPos = 90; //variable to store the servo position from last run of the code

const int b1Pin = 6;  //constant to store button1 pin number
int b1State = 0;      //constant to store button1 state

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
  pinMode (b1Pin, INPUT);  //sets the button pin as input

  myservo.write(90);  //set the servo to 90


void loop() {

  b1State = digitalRead(b1Pin); //check the button pin and store it's state 
  if ((b1State == HIGH) && (pos <= 180)){  //if button1 is pressed and the pos variable has not gone over 180
    pos = lastPos + 1;                  //add one to the current position and store in 'pos' 
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(5);                       // waits 5ms for the servo to reach the position
    lastPos = pos;                  // set lastPos to the current position for checking next time round


Extension exercise:

  • Add another if statement to turn on the built in LED on pin 13 if both buttons are pressed and an else statement to turn it off again (you may want to refer to the 'Blink' sketch in the Examples > Basic section)

Click on a link 

Exercise 1 - Digital LED strip and the 'for' loop

Exercise 3 - 7 segment display and the 'switch case' statement