Buttons & Servos

Hola,

We are trying to get a servo to move using one button. One push should send it from 0 deg to 180 deg, and the next push should send it back to 0 deg, and so on and so forth. It seems like an easy thing.

We coded it so that the button triggers a 'sub' void.

Several hours later ........ What is the problem?

Thx

#include <Servo.h> 
#define LID_B A2          //TEMP Lid open / close  button

int servoPin = 4; 
Servo Servo1; 
//int pos = 180;

void setup() { 
   
   pinMode(LID_B, INPUT_PULLUP);
   Servo1.attach(servoPin); 
  
   
   
}
void loop(){ 
  if(digitalRead(LID_B) == LOW) //functions based off of button pulling input pin LOW 
      {
        open_close();
        

      }
}
void open_close(){

  int pos = Servo1.read();

 if (pos > 10)
    {
      Servo1.write(180);
      Servo1.read();
      delay(5);
    }
    
if (pos < 170)
 {
  
      Servo1.write(0);
      Servo1.read();
      delay(5);
 }
}

Servo__05.ino (610 Bytes)

You need to detect when a button becomes pressed, not when it is pressed. Look at the StateChangeDetection example in the IDE. When the button becomes pressed move the servo

Thanks - we looked at that example (we are really thick at times, so please forgive):

We had the button switching things on, but it appears to us the problem is reading the servo position and then moving it accordingly. Isn't the button just triggering the same if/else loop over and over?

Not trying to be tricky - just trying to understand.

Thanks,

The point is that you don't want to trigger a servo move except when the button becomes pressed