Sunday, November 17, 2013



A quick video of the servo working properly with the switch. This was done using the code below.

//This is the initial code. Code will eventually be modified for a switch instead of a potentiometer.
#include <Servo.h>      //Including the servor library in the code

// this constant won't change:
const int  onoffswitch = 2;    // the pin that the pushbutton is attached to
// Variables will change:
int switchCounter = 0;   // counter for the number of button presses
int switchState = 0;         // current state of the button
int lastSwitchState = 0;     // previous state of the button
//Set servo as myservo
Servo myservo;                    

void setup () {                                  //Starting off the code
  
    // initialize the button pin as a input:
  pinMode(onoffswitch, INPUT);

    //myservo is set to pin 12
  myservo.attach(12);

    //and is placed at 180 degree
  myservo.write(180);
  
    // initialize serial communication:
  Serial.begin(9600);
 }

 void loop ()                                     //Start loop
 {
 // read the switch input pin:
  switchState = digitalRead(onoffswitch);

  // compare the switchState to its previous state
  if (switchState != lastSwitchState)
      {
        // if the state has changed, increment the counter
        if (switchState == HIGH) {
          // if the current state is HIGH then the button
          // went from off to on:
        myservo.write (180);        //so place servo at 180 degree so that
                                    //the finger will push the switch back to off  
      switchCounter++;
      Serial.println("on");
      Serial.print("number of button pushes:  ");
      Serial.println(switchCounter);
        delay(100);                 //pause for 10th of a second
    
      }         //close IF statement
     else{                
        myservo.write (25);         //move servo to position 25 degree
        delay (100);                //then pause for 10th of a second
    
      }        //close ELSE statement
    
  }            //close IF statement
  // save the current state as the last state,
  //for next time through the loop
  lastSwitchState = switchState;
}              //close LOOP

No comments:

Post a Comment