Move Servo Automatically with 2 Buttons

Hello Everyone,

I am a veteran programmer but I am new to Arduinos. I want to push a button and have a servo move to a certain position. I do not want to hold down the button just hit it 1 time and have it move to a certain position. Then hit the second button to move to a different position. Can you assist me with my code?

#include <Servo.h>
int button1 = 2; //button pin, connect to ground to move servo
int button2 = 4;
int press1 = 0;
int press2 = 0;
Servo servo1;

void setup()
{
  pinMode(button1, INPUT);
  servo1.attach(9);
  digitalWrite(4, HIGH); //enable pullups to make pin high
}

void loop()
{
  press1 = digitalRead(button1);
  press2 = digitalRead(button2);
  if (press1 == LOW)
  {
    servo1.write(160);
  }
  else {
    servo1.write(20);
  }
}

The state change detection example in the IDE will help do what you want. It shows how to detect a transition (versus state). Look in File, Examples, Digital. Using state change you can tell your servo to move to a position when the switch goes from low to high, for example. The low or high levels and the other transitions can be ignored.

Simple two button servo code.

/zoomkat servo button test 12-29-2011
// Powering a servo from the arduino usually *DOES NOT WORK*.

#include <Servo.h>
int button1 = 4; //button pin, connect to ground to move servo
int press1 = 0;
int button2 = 5; //button pin, connect to ground to move servo
int press2 = 0;
Servo servo1;

void setup()
{
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  servo1.attach(7);
  digitalWrite(4, HIGH); //enable pullups to make pin high
  digitalWrite(5, HIGH); //enable pullups to make pin high
}

void loop()
{
  press1 = digitalRead(button1);
  if (press1 == LOW)
  {
    servo1.write(170);
  }    
  
  press2 = digitalRead(button2);
  if (press2 == LOW)
  {
    servo1.write(10);
  }
}

Awesome... thanks guys I will give that a try tonight.

Worked great, thanks!