Go Down

Topic: button fails (Read 1 time) previous topic - next topic


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 ;)

thanks anyway

MC. kintoshli

Code: [Select]

int time = 10000;     
int einlauf = 5000;

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

void setup(){
  pinMode(button1, INPUT);
  pinMode(buzzpin, OUTPUT);
  pinMode(valve, OUTPUT);
  pinMode(led, OUTPUT);


void loop(){
  digitalWrite(buzzpin, HIGH);


  digitalWrite(buzzpin, LOW);
  digitalWrite(led, LOW);
  digitalWrite(valve, HIGH);
  digitalWrite(led, HIGH);
  digitalWrite(valve, LOW);
  digitalWrite(led, LOW);
  void buttonwait(){
    while(digitalRead(button1) == 0){


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

Also look into debouncing.
Please post technical questions on the forum, not by personal message. Thanks!

More info: http://www.gammon.com.au/electronics


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.
The art of getting good answers lies in asking good questions.


thanks! it works now!

Go Up