Serial.println() in if statement

Hi, I have a problem with a simple program to check if button is pressed.

The button is connected to pin 9 and GND.

This is my code:

int but1 = 9;

int read1 = 0;

bool pressed = false;

void setup() {
  pinMode(9, INPUT);
  Serial.begin(9600);
}

void loop() {
  if(digitalRead(but1) == 0){
    if(read1 < 10){
      read1++;
    }
  }
  else{
    read1 = 0;
  }
  
  if(read1 == 10){
    pressed = true;
  }
  else{
    pressed = false;
  }

  Serial.println(pressed);
}

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?

  pinMode(9, INPUT);

Change that line to:

  pinMode(9, INPUT_PULLUP);

And try it.

Digital pins.

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.

digitalRead returns randomly 1 or 0

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.

Just a coincidence.

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".

It WAS a coincidence, by definition, regardless of whether there is a causal connection, which is extremely unlikely in any case.