Vending Machine Project

I am having trouble with the way the states switch. When i push the button connected to pin 3, The variable "button" becomes 1 but instead of going back to 0 when the button is not pressed it remains at 1 with 3 sec delays every interval in the serial monitor. Any ideas on how to control this variable successfully?

int button;
int state=0;
int nextState=0;

#include <LiquidCrystal.h>

LiquidCrystal lcd(4,5,6,7,8,9);

void setup() {

lcd.begin(16,2);
lcd.clear();
pinMode(3,INPUT);
Serial.begin(9600);

}

void loop() {

switch(state)
{
case 0:

lcd.setCursor(0,0);
lcd.print("Hello, please");
lcd.setCursor(0,1);
lcd.print("deposit a coin");

break;
case 1:
lcd.clear();
lcd.setCursor(0,0);
lcd.print("payment made");
lcd.setCursor(0,1);
lcd.print("$0.25");

delay(3000);

break;

case 2:

lcd.clear();
lcd.setCursor(0,0);
lcd.print("payment made");
lcd.setCursor(0,1);
lcd.print("$0.25");
delay(3000);

break;

case 3:
lcd.clear();
lcd.setCursor(0,0);
lcd.print("payment made");
lcd.setCursor(0,1);
lcd.print("$0.50");
delay(3000);
break;

default:

lcd.setCursor(0,0);
lcd.print("Hello, please");
lcd.setCursor(0,1);
lcd.print("deposit a coin");
break;

}

switch(state)
{
case 0:
if (digitalRead(3)==HIGH)
{nextState=1;}
else
{nextState=0;}
break;

case 1:
if(digitalRead(3)==HIGH)
{nextState=2;}
else
{nextState=1;}

break;
case 2:
if(digitalRead(3)==HIGH)
{nextState=2;}
else
{nextState=3;}
break;
case 3:
nextState=0;
break;
default:
nextState=0;
break;
}
state=nextState;

Serial.println(state);
}

Do you have a pull-down resistor fitted to the input to ensure it is pulled low when the button is released?

Or is it allowed to float?

im not sure what you mean, there is a resistor connected to the button and the lcd is connected through a potentiometer.... Do i need another resistor somewhere?

randytudor52:
im not sure what you mean, there is a resistor connected to the button and the lcd is connected through a potentiometer.... Do i need another resistor somewhere?

Please show us the wiring.

i thought thats what i had... can you tell me (based on the picture) where i need to put the resistor, please?

That is what you have, but it's not visible in the first picture.

Are the ground rails on the two sides of the breadboard connected? Check with multimeter - some breadboards connect those internally, others don't.

yes, they are connected, i get a reading on the multimeter when i am pushing the button down, when i release i dont get anything, which is what i want. I suspect the problem is with the code. the digitalRead(3) gets stuck in HIGH so it never leaves case 2 in the switch/case.

Put some logging in there - ie, print debug info to serial, so you can see what code is being run and what code isn't, and narrow down what's going on. For for starters, print out the state of pin 3 so you can see if it's continually reading high, or something else going on.