Monday, August 17, 2015

Servos and Interrupts

I got my daily fix of eBay parts in the mail so I hooked up my shiny new limit switch to D2 and attached a CHANGE interrupt to it.  The interrupt stopped a servo that was running Sweep.


#include  
 
Servo myservo;  // create servo object to control a servo 
                // a maximum of eight servo objects can be created 
 
int pos = 0;    // variable to store the servo position 
volatile int state = LOW;
 
void setup() 
{ 
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  attachInterrupt(0, pressed, CHANGE); 
} 
 
 
void loop() 
{ 
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees 
  {                                  // in steps of 1 degree 
    myservo.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
    while(state == HIGH) {
      delay(15);
    }
  } 
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees 
  {                                
    myservo.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
    while(state == HIGH) {
      delay(15);
    }
  } 
}

void pressed()
{
  state = !state;
}

No comments:

Post a Comment