2nd If statement not working

Hey everyone,

Im sure this is super simple but i am having a bit of difficulty with this. I have two lights and two photo transistors, I would like it so that when one light turns on it then makes the other light turn on. I have delays in there so it will kind of look like they are talking to each other, All depending on light readings from the photo transistor.

Currently only 1 of the “if” statements work at a time. If I have one in the code it works, but when I add the second “If” statement only the second one works, and when I delete it the 1st one works again. Any help would be much appreciated :slight_smile:

Thank you
Rory

const int light1 = 9;
const int light2 = 10;
int sensor1;
int sensor2;

void setup() {

  Serial.begin(9600);
pinMode(10,OUTPUT);
pinMode(9,OUTPUT);
}

void loop() {
sensor1 = analogRead(A0);
sensor2 = analogRead(A1);


Serial.println(sensor1);
Serial.println(sensor2);


//1st If statement
if (sensor1 < 40 ) {
  digitalWrite(10,LOW); 
}

  else {
    
    digitalWrite(10,HIGH);
  }



//2nd if statement

if (sensor2 < 40 ) {
  digitalWrite(10,LOW); 
}

  else {
    
    digitalWrite(10,HIGH);
  }


}

Hello Rory,
If statements always work.

You need to tell us what you expect to happen and what happens instead, and how you know.

It would be easier to help if you included a schematic.

You can not know for sure the if statement works or not by just watching the LED state. The value from each sensor may be different. You had better to use Serial.println() function inside "if" statemen to know whether if statement works or not.

You intend sensor 1 and sensor2 to use the same LED pin?

You declare these

const int light1 = 9;
const int light2 = 10;

but where do you use them?

PerryBebbington:
Hello Rory,
If statements always work.

You need to tell us what you expect to happen and what happens instead, and how you know.

It would be easier to help if you included a schematic.

What i intend to happen is when each photo transistor goes above a reading of 40 it turns a light on.
But whats happening is that depending if I have one or two of the "if" statements in my code only one of the lights will light up.
If I have one if statement then the light corresponding to that statement will turn on if it's sensor goes above 40
but
If i have both of the if statements in the code ,as is in the code i posted, only the 2nd if statement works and the 1st one stops working

IoT_hobbyist:
You can not know for sure the if statement works or not by just watching the LED state. The value from each sensor may be different. You had better to use Serial.println() function inside "if" statemen to know whether if statement works or not.

Great Idea ! i tried that and realized that the if statement was working its just that I had "10" in place for both instead of 9 for one and 10 for the other, all fixed now thank you very much !