If...Else loop, won't reinitiate?

Hello again,

I’ve got a simple system, which is initiate with a pushbutton: A spring engages, it then turns off while a Vacuum simultaneously turns on, and a counter adds 1 to its count.

What i’m trying to do is push the button, let the cycle run one time and then halt until the button is pushed again. It runs fine for the first cycle but will not run if the button is pushed a second time.


//Pin 8 is Relay 0, Pin 7 is Relay 1, Pin 9 is Button Pin

int Button = 9;
int Spring = 8;
int Vac = 7;

int ButtonState = 0;
int Counter;

void setup()
pinMode(Spring, OUTPUT);
pinMode(Vac, OUTPUT);
pinMode(Button, INPUT);

void loop()
ButtonState = digitalRead(Button);

if ((ButtonState == HIGH) && (Counter < 1))
digitalWrite(Spring, HIGH);
digitalWrite(Spring, LOW);


digitalWrite(Spring, LOW);
digitalWrite(Vac, LOW);

if ((ButtonState == HIGH) && (Counter < 1))

Of course it won’t go again. If ButtonState is HIGH and the counter is less than 1 then you do some stuff and add one to the counter. On the next go round it doesn’t matter what the ButtonState is because Counter is now 1 or more so this whole thing is false and it goes to the else statement.

Maybe you want to reset the counter to 0, or maybe you shouldn’t be testing the counter with the button state. Which one you want isn’t entirely clear from your description.

A good troubleshooting/debugging technique is to send your variable values out to the serial monitor. i.e. You can see the button state and the Counter value before your if-statement.

You also never initialize Counter, so you're lucky it works the first time.

You do initialize ButtonState, which is good practice, but not really necessary since you don't do anything with that variable until after you read the button.

DVDdoug: You also never initialize Counter, so you're lucky it works the first time.

It's global so the compiler initializes it to zero. If it were a local variable that might be trouble, but the compiler saved him here.

asawheb92: WHAT DO?

Well, please start by going and reading the instructions, then go back and modify your post to mark up the code as such rather than incorrectly as a "quote" so we can deal with it comfortably and accurately.

It's very interesting that you never use 'Counter' at all, except to stop your program from working.