Bolean false and serial println

Hello,

When I tried to run serial printf on the bolean function below, if the state is false, the output isn’t printing 0 but instead some random number. But, when the state is one, 1 is been printed. The bauld rate has been set to 9600.

This program suppose to read input from a motion sensor.

boolean sensor(){
Serial.begin (9600);
digitalRead (_sensorPin);
boolean state = true;

if (!digitalRead (_sensorPin)== HIGH){
boolean state = false;
}

Serial.println (state);
return state;
}

You have two state variables.
Why?

Please remember to use code tags when posting code

TheMemberFormerlyKnownAsAWOL:
You have two state variables.
Why?

Please remember to use code tags when posting code

Thanks for your reply.
what do you mean by two state variables?

You have defined two variables called “state”, the second of which has very limited scope.

I also suspect you don’t want Serial.begin in your function.

TheMemberFormerlyKnownAsAWOL:
You have defined two variables called "state", the second of which has very limited scope.

I also suspect you don't want Serial.begin in your function.

I thought it is only one variable that I have set to true and then false.

boolean sensor(){
      Serial.begin (9600);
      digitalRead (_sensorPin);
      boolean state = true; <<< one variable here
   
      if (!digitalRead (_sensorPin)== HIGH){
      boolean  state  = false;  <<< another variable here
      }

     
      Serial.println (state);
      return state;
    }

Also, if you’re not doing anything with the result of the first digitalRead, you should make it clear to readers (void)digitalRead (_sensorPin);

You can assign booleans directly boolean state = digitalRead (_sensorPin) == HIGH;

Thank you so much.
This line of code has solved my issue.

boolean state = digitalRead (_sensorPin) == HIGH;

At least I have learned to define the state variable only 1 time.

Hi,
What do you expect this line to do?

   digitalRead (_sensorPin);

This may help;
https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/

Tom... :slight_smile:

TomGeorge:
Hi,
What do you expect this line to do?

   digitalRead (_sensorPin);

This may help;
digitalRead() - Arduino Reference

Tom… :slight_smile:

See reply #6