Servo toggle 180 on press and rotate back again on press

Hey guys I’m on Day 2. I have one button on the board that I’d like to toggle a servo 180 degrees and keep it there until the button is pressed again and it returns to 0.

Here is some basic code I got from a post on these forums that I modified and added a new variable “swtch” to act as an ON/OFF variable, however it doesn’t seem to be working. I think I might be trying to use buton1 = LOW as a substitue for some kind of onPress function.

Thanks for looking

//zoomkat servo button test 7-30-2011

#include <Servo.h>
int button1 = 7; //button pin, connect to ground to move servo
int press1 = 0;
int swtch = 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);
  
  // on press down turn one way
  if (press1 == LOW && swtch == 0)
  {
    servo1.write(160);
    swtch = 1;
  }
  
  if (press1 == LOW && swtch == 1)
  {
    servo1.write(0);
    swtch = 0;
  }
}

I haven't time to look properly, but there's a numbering discrepancy in what you're doing with the input pin...

You set button1 as input, and button1 is pin 4. But then you make pin7 high: I suspect those should both be either 4 or 7.

That might be part of your problem, seeing as you are hoping for active low I think, which does require the pullup, which with your current code won't be right.

Newer way of doing pullups is not to set a pin as input in one line, and high in another. This way is simpler:

pinMode(7, INPUT_PULLUP);

As well as sorting out the numbering you should (at least for testing) put a substantial delay (perhaps 2000 millisecs) after each servo instruction to give the servo time to move and to give you time to see what is happening.

Remember that the servo.Write(ddd) doesn't wait for the servo to move.

...R