Everything runs as it should, but when i replace the last line with something like:
if(pressed){
Serial.println("button pressed")
}
then it prints out "button pressed" all the time, also when the button isn't pressed. When I replace println with digitalWrite (and connect a LED) the same thing happens. Whats wrong?
You are detecting when the button is pressed, not when the button becomes pressed
You also need to hold the input at a known state even when the button is not pressed. Set the pinMode() of the input using INPUT_PULLUP to activate the built in pullup resistor
ok, it works after replacing INPUT with INPUT_PULLUP. Thanks.
I still don't understand what was wrong.
I know that when input pin isn't connected to anything digitalRead returns randomly 1 or 0, but there are virtually never more than 10 zeros in a row (that's why my program was working in the first case). I don't get how removing one println() could break a program.
That is not really true. Depending on conditions the pin can be stuck HIGH or LOW. The state of a floating pin is undefined, or in other words, not predictable.
My point is that the program stopped working after removing println(), like if printing a value would affect it in some way.
I'm just courious how romoving println() could change anything.
I don't think it was a coincidence. Your code said Serial.println(pressed); you forgot the " " around pressed so arduino was working with pressed.... the command you used as the bool statement, instead of the word "pressed".