Arduino Servo's with button switch!I

Hello!

I am new with Arduino and I am practicing to get better with it.
i have made a program with a single Servo motor and a push button.
I have written a program with 3 different Servo programms.
If i give him power he will do program 1, if i push the button he will do first program 1 and then program 2.
If i push the button then he will do first 2 en then program 3.

Does anyone explain to me why if I push the button why he first do the ‘program he has already done’ and then do the new program?

Sorry for my bad english!

This is the code:

const int motorPin = 9;
const int buttonPin = 2;

int buttonState = 0;
int lastButtonState = 0;
int buttonPushCounter = 0;

void setup()
{
pinMode(motorPin, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);

}

void loop() {
buttonState = digitalRead(buttonPin);

if(buttonState != lastButtonState)
{
if (buttonState == 1){
buttonPushCounter++;

}
lastButtonState = buttonState;
if (buttonPushCounter == 1 ){

motorOnThenOff();
Serial.println(“on”);
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
}

if (buttonPushCounter == 2) {

motorAcceleration();
Serial.println(“on”);
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);

}

if (buttonPushCounter == 3) {

motorOnThenOffWithSpeed();
Serial.println(“on”);
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
}

if (buttonPushCounter >= 4) {
buttonPushCounter =0;
}

}
}

void motorOnThenOff(){
int onTime = 2500;
int offTime = 1000;

digitalWrite(motorPin, HIGH);
delay(onTime);
digitalWrite(motorPin, LOW);
delay(offTime);
}

void motorOnThenOffWithSpeed(){

int onSpeed = 200;
int onTime = 2500;

int offSpeed = 0;
int offTime = 1000;

analogWrite(motorPin, onSpeed);
delay(onTime);
analogWrite(motorPin, offSpeed);
delay(offTime);
}

void motorAcceleration(){
int delayTime = 50;

for(int i = 0; i < 256; i++){
analogWrite(motorPin, i);
delay(delayTime);
}

for(int i = 255; i >= 0; i–){
analogWrite(motorPin, i);
delay(delayTime);
}
}

I know it is a bit messy:p

Thanks for helping!

pinMode(buttonPin, INPUT);

But, you are not enabling the pullup resistor. So, you MUST have an external resistor. Do you? How IS the switch wired?

Until you explain that, we can’t help you.

Simple servo button test code you can try just by touching pin 4 to ground for the button. Note that a “debounce” delay or other fix will smooth out the servo operation just touching wires for the switch button.

//zoomkat servo button test 7-30-2011

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

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

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