Can't change a variables value inside an if statement

Hi, my code goes something like

global variable
int x = 1;

void loop() {

  if (digitalRead(2) == HIGH) {
         x = 0;
   }

}

But, when I 'serial.monitor' what x is, after I have triggered the sensor, it remains as 1.

for some reason if I have an if statement that uses a 'digital input' then it won't change the value for x. For example if I just had if (x = 1) { x = 0; } that would work

Does a 1 ever print out?

yes. It will print out. perhaps there is another technique for what I want to do. I have 10 sensors, I want to save to an array[10] if at some point one of the sensors has or has not been triggered.

To elaborate, if all the sensors are off and one is triggered then It will run different code to if a sensor is activated but is not the first sensor.

The why do you think that x is not set = 0 in the conditional block?

I'd guess the obvious - That input-2 is not high when you're reading it. What happens if you disconnect the sensor and hold the pin high.

I haven't tried this. I was just wondering if there is some special situation in Arduino that makes if statements with digitalread have some special conditions. I might simple my program and see if something else is causing the issue.

Hi, well the code is like

if (digitalRead(2) == HIGH) {
x = 0;
}
Serial.println(x);

and it always prints 1. even if I hold my hand on the sensors.

if I put statements like
if (digitalRead(2) == HIGH) {
x = 0;
Serial.println("I got to here");

}

it prints "I got to here" no problem. But the issue is it doesn't change to variable x

Yes, if you can provide a simplified example of your program which demonstrates the issue, I'm certain you'll get the help you need.

You should post code by using code-tags.
There are automatic functions for doing this in the Arduino-IDE.

Three steps:

1)press Ctrl-T for autoformatting your code
2)do a right click with the mouse and choose "copy for forum"
3)paste clipboard into write-window of a posting

You should post all your code.

Did you set pinmode?

void setup() {  // initialize digital pin 13 as an output.
   pinMode(2, OUTPUT);
}

// the loop function runs over and over again forever

void loop() {
   digitalWrite(2, HIGH); 
   delay(1000);    digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
   delay(1000); 
}

Does that work?

@papahaha, your topic has been moved to a more suitable location on the forum. Installation and Troubleshooting is not for problems with your project :wink: See About the Installation & Troubleshooting category.

Please post your complete code; and please post it using code tags (the </> button above the reply window).

Actually this is wrong. You probably meant if (x == 1) { x = 0; }

Please post your entire sketch and how the digital input is wired and what type of sensor it is.

1 Like