Arduino Uno rev 3 servo motor push button

Hi, I am working on a project where i am controlling a servo motor to do one loop of swaying one way and back by just one press of a push button. I have programmed it now to do the loop of swaying to one position and back to the origin, however the servo motor continues doing the loop forever and doesnt stop. I am very new to all this so any advice would be great thanks!

Code:

#include <Servo.h>
int button = 14; //button pin, connect to ground to move servo
int press = 0;
int pos = 0;
Servo servo;
boolean toggle = true;

void setup()
{
pinMode(button, INPUT); //arduino monitor pin state
servo.attach(7); //pin for servo control signal
digitalWrite(5, HIGH);
}

void loop()
{
press = digitalRead(button);
if (press == LOW)
{
if(toggle)
{for (pos = 0; pos <=40; pos += 1){
servo.write(pos);
delay(15);}
for (pos = 40; pos >= 0; pos -=1){
servo.write(pos);
delay(2);
}
}
}
press = digitalRead(button);}

If your button is connected to ground like your comment says, then you need to define the pin as INPUT_PULLUP to enable the internal pullup on that pin or it will "float" when the button is not pressed which means it could read HIGH or LOW randomly.

And as well, there's no point doing a digitalRead(button) at the bottom of loop() and then a tiny instant later when it loops round to the top doing it again. Just the one at the top is enough. Also "if (toggle)" does nothing because you initialise toggle as true and never change it.

If you really need only one back and forth of the servo even if the button stays pressed for too long then you want to be starting the movement when the button BECOMES pressed not just whenever it happens to be pressed. Have a look at the StateChangeDetection example in the IDE for how to do that.

Steve

I wonder if OP was planning to actually use the variable "toggle"?

You could initialise toggle false, set toggle true when button is pressed, then use its true-ness to trigger the sweep (but not nested inside the if of the button, where it is right now), immediately setting it false. Then as long as the button is released before the sweep completes, and doesn't therefore get seen as a re-start, it will do the sweep only once.

You COULD do all sorts of things with a variable called toggle. All I was pointing out was that the code we have seen doesn't do any of them.

I can't see much point commenting on code that might have been written but wasn't.

Steve