Servo Motor Experiments

After completing the Servo Motor project, test yourself by trying these experiments.

1 Instead of just making the servo motor turn to 0 degree and 180 degree, make the servo motor sweep slowly back and forth.










The for loop increments the variable i from 0 to 180 in increments of 1.
The write command tells the servo motor to turn to the degree that is currently stored in the variable i.



This second for loop causes the servo motor to rotate back.
// need this for the servo motor
#include <Servo.h>
Servo myservo;

void setup() {
  myservo.attach(9);  // the servo motor is connected to pin 9
}

void loop() {
  for (int i=0; i<=180; i++) {
    myservo.write(i);
    delay(20);
  }

  for (int i=180; i>=0; i--) {
    myservo.write(i);
    delay(20);
  }
}
2 Modify experiment 1 to make the servo motor turn faster in one direction and slower in the other direction.
3 Add a 1 second pause between the back and forth sweeps from experiment 1.
4 Make the servo motor turn to 0 degree when you press a push button, and to 180 degree when you release the push button.
// need this for the servo motor
#include <Servo.h>
Servo myservo;

int buttonPin = 2;

void setup() {
  Serial.begin(9600);
  myservo.attach(9);  // for the servo motor
}

void loop() {
  int buttonValue = digitalRead(buttonPin);
  Serial.println(buttonValue);
  
  if (buttonValue == HIGH) {
    myservo.write(0);
  } else {
    myservo.write(180);
  }
  delay(500);
}
5 Make the servo motor turn to 0 degree when there is light, and to 180 degree when there is no light.
// need this for the servo motor
#include <Servo.h>
Servo myservo;

// need this for the light sensor
int sensorPin = A0;

void setup() {
  Serial.begin(9600);
  myservo.attach(9);  // for the servo motor
}

void loop() {
  int sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
  
  if (sensorValue > 600) {
    myservo.write(0);
  } else {
    myservo.write(180);
  }
  delay(500);
}
NOTE:Use of the Servo motor commands will interfere with the analogWrite command on pins 9 and 10. This means that you cannot use the analogWrite command on pins 9 and 10, and use the Servo commands (even if not at the same time).