Question about sequencing

Hello all,
I'm trying to understand why the following program is responding in this matter. In the program below, If the photoresist for L1 is triggered so that L1 light illuminates 1st, L2, when covered comes on and goes off when uncovered. However, If the photoresistor for L2 is triggered first, when the photoresistor for L1 is covered, L1 does not come on. If I uncover lane 2 momentarily while keeping L1 covered, the led for lane 1 comes on and L2 comes back on, but if L1 is uncovered, L1 stays on until L2 is uncovered.
Is this a quirk of Arduino or is it a coding error? WHat is the logic for it to perform this way?

void setup() {

  Serial.begin(9600);
  pinMode(9, OUTPUT); //Lane 1 prestage. initialize the LED pin as an output
  pinMode(A6, INPUT);   //Lane 1. initialize the LDR pin as an input
  pinMode(8, OUTPUT); //Lane 2 prestage
  pinMode(A7, INPUT); // Lane 2 
}

void loop() {

int ldrStatus1 = analogRead(A6); //read the status of the LDR value

     if (ldrStatus1 <=300) {

    digitalWrite(9, HIGH); //turn LED on
    }
  else {

    digitalWrite(9, LOW); //turn LED off
    
int ldrStatus2 = analogRead(A7);

     if (ldrStatus2 <=300) {

    digitalWrite(8, HIGH); //turn LED on
    }
  else {

    digitalWrite(8, LOW); //turn LED off
  }
}
}
1 Like

If you use the IDE's auto format tool, your code's logic may become clearer.

Hello

I think your brackets are at the wrong place

if (ldrStatus1 <= 300)
  {
    digitalWrite(9, HIGH); //turn LED on
  }
  else
  {
    digitalWrite(9, LOW); //turn LED off

    int ldrStatus2 = analogRead(A7);
    if (ldrStatus2 <= 300)
    {

Did you mean to have the ldrStatus2 stuff inside the 'else' clause with digitalWrite(9, LOW); //turn LED off?

This makes the two tests independent.

void loop()
{
  int ldrStatus1 = analogRead(A6); //read the status of the LDR value

  if (ldrStatus1 <= 300)
  {
    digitalWrite(9, HIGH); //turn LED on
  }
  else
    digitalWrite(9, LOW); //turn LED off

  int ldrStatus2 = analogRead(A7);

  if (ldrStatus2 <= 300)
  {
    digitalWrite(8, HIGH); //turn LED on
  }
  else
    digitalWrite(8, LOW); //turn LED off
}

And on an UNO/Nano/Mega you can simplify quite a bit because HIGH==true==1 and LOW==false==0

void loop()
{
 // LED on, iff analog input <= 300
 digitalWrite(9, analogRead(A6) <= 300);
 digitalWrite(8, analogRead(A7) <= 300);
}

I use the online Arduino editor. What does the auto- format tool do? Will it point out errors in my coding?

It indents code, which helps to highlight code structure.