button fails

Hey there

I'm kinda new to Arduino and this is my first Project really involving it not just "playing".

I'm having an issue with my buttonwait() function:
It works when the sketch runs but after 4 or 5 seconds it automatically exits the while loop.

what am i doing wrong?

PS: I also appreciate corrections in bad coding :wink:

thanks anyway

MC. kintoshli

int time = 10000;     
int einlauf = 5000;


int button1 = 10; //set pins
int buzzpin = 11;
int valve = 12;
int led = 13;

void setup(){
  Serial.begin(9600);
  
  pinMode(button1, INPUT);
  
  pinMode(buzzpin, OUTPUT);
  pinMode(valve, OUTPUT);
  pinMode(led, OUTPUT);
 
}

void loop(){
  
  Serial.println("waiting...");
  
  delay(time);
  
  Serial.println("DRINK!");
  digitalWrite(buzzpin, HIGH);
 
  buttonwait();
 
  Serial.println("filling...");
  digitalWrite(buzzpin, LOW);
  digitalWrite(led, LOW);
  digitalWrite(valve, HIGH);
  
  delay(einlauf);
  
  Serial.println("ready!");
  digitalWrite(led, HIGH);
  digitalWrite(valve, LOW);
  
  buttonwait();
  
  delay(1000);
  
  digitalWrite(led, LOW);
  }
  
  void buttonwait(){
    while(digitalRead(button1) == 0){
  delay(50);
  }
  }

You need to look for transitions. i.e., was low, is now high. Not just "is now high".

Also look into debouncing.

mackintoshli:
after 4 or 5 seconds it automatically exits the while loop.

For that to happen, digitalRead() must be returning a non-zero value. Have you got an external pull-down resister on pin 10? If not, presumably the pin is floating (not connected to anything) when the switch is open - in this case reading the pin state will return arbitrary values. The solution to this is to use a pull-up or pull-down resister.

The Arduino provides an internal pull-up resister which you could use for this, but to use that you'd need to reverse the polarity of this pin so that it is normally held high by the pull-up resister and is pulled low by the switch. You'd have to change "while(digitalRead(button1) == 0)" too so that it waits for LOW rather than HIGH.

So have you got an example? Sorry i dont get how i'd need to wire it up...

So have you got an example? Sorry i dont get how i'd need to wire it up...

The best way, in my opinion, to wire a switch involves hardware and software. Connect one leg of the switch yo ground. Connect the other leg to a digital pin. Then, use pinMode() to set that pin as INPUT. Finally, use digitalWrite() to set that pin HIGH, enabling the internal pullup resistor.

When the switch is pressed, it will read LOW. When not pressed, it will read HIGH. While these initially seem backwards, they are easier to remember if you consider that a momentary contact pushbutton switch top is high when not pressed and low(er) when pressed.

thanks! it works now!