Why is my input always high?

Firstly, I tried this code on a simulator (Autodesk circuits), so maybe the simulator is wrong, but this is my problem:

I wrote this code, to make leds flash alternating, while a button is pressed:


int start = 2; int led1 = 3; int led2 = 4;

void setup() {

pinMode(start, INPUT); pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); }

void loop() {

while(digitalRead(start)==HIGH){ digitalWrite(led1, HIGH); delay(1000); digitalWrite(led1, LOW); delay(50); digitalWrite(led2, HIGH); delay(1000); digitalWrite(led2, LOW); delay(50); } }


The thing is, the input always seems to be high. The leds are always flashing, whether the button is pressed or not. But strangely, when I set the button "start" to output, it does exactly what I want it to do. Is this a problem with the simulator, or am I missing something in my code?

Let me guess, no resistor on the switch?

Connect the button between GND and the pin and switch to pinMode(startPin, INPUT_PULLUP). You will now read a LOW when the button is pressed but that’s just a simple flip of the logic.

And yeah, simulators are just crap. Arduino itself is cheap enough to just use that.

 while(digitalRead(start)==HIGH){
   digitalWrite(led1, HIGH);
   delay(1000);
   digitalWrite(led1, LOW);
   delay(50);
   digitalWrite(led2, HIGH);
   delay(1000);
   digitalWrite(led2, LOW);
   delay(50);
}
}

The way this while loop is written, there us 2100 milliseconds of delay time between every read of the pin. In order for this to see the button press, you may have to hold the button down for over 2 seconds. It would have to be held down right at the end of the flash sequence so that when the while loop repeats and checks the pin again it will see it as HIGH.

If you want the program to be responsive to button pushes, then you have to get rid of all the delay calls and long while loops and embrace the "Blink Without Delay" example.