Friday, October 30, 2015

Learning how to drive a Servo

This Code makes the Servo switch between 2 points in the 180 degree range repeatedly.

#include <Servo.h>

boolean buttonCheck = false;

int buttonTimer = 0;

int servoAmount = 1700;

int valid = LOW;

int pin = 8;

int MAX = 5000;

int MIN = 600;

Servo servo1;

void setup(){
  servo1.attach(2);
  pinMode(pin,INPUT);
}

void loop(){
  
  valid = digitalRead(pin);
  
  if (buttonCheck == false) {
    if (valid == HIGH) {
      
      //turn on the fact that the button is being pushed
      buttonCheck = true;
      
      //switches the variable controlling the position of servo
      if (servoAmount == MAX) {
        servoAmount = MIN;
      }
      else {
        servoAmount = MAX;
      }
    }
  }
  
  //timer for the button check
  if (buttonCheck == true) {
    // should add 1 microsecond to the timer
    buttonTimer = buttonTimer + 1;
    
    //stops the timer once it gets to half a second
    if (buttonTimer == 500) {
      buttonTimer = 0;
      buttonCheck = false;
    }
  }
    
  
  //controls where the servo should be
  //servo should run 1700 to 1200
  servo1.writeMicroseconds(servoAmount);
  
  //delays 1 microsecond
  delay(1);

}

A picture of the Servo that we used:


In the future we can use the code that we used to drive the Servo's to drive speed controllers for motors and also continuous servos. Learning how to drive a Servo is an important skill in robotics.

No comments:

Post a Comment