Changing a variable based on an analog sensor

Hi All,

Please can I have some help? I can't work this out, I have tried the reference pages and other examples but with no success! It's probably something very simple I'm missing

Below is my complete sketch, I am trying to change the variable "state" depending on the light levels received at the LDR. I have the serial monitor open, the LDR value is going between 850 ish when in sunlight and down to 4 when I cover it, but the state isn't changing.

int LDR_new = 0;

int state = 0;

void setup()
{
  pinMode(12, OUTPUT);
  
  Serial.begin (9600);
}

void loop()
{
  LDR_new = analogRead(5);
  
  if(LDR_new > 650) 
  {
    state = 1; 
  }

  if(LDR_new < 650)
  {
   state = 0; 
  }
  
  if(state == 0)
  {
   digitalWrite(12, LOW);
  }
  
  if(state = 1);
  {
    digitalWrite(12, HIGH);
  }
  
  Serial.print ("The state value is ");
  Serial.print (state);
  Serial.print ("The LDR value is ");
  Serial.print (LDR_new);
  delay(2000);
  
}
  if(LDR_new > 650) 
  {
    state = 1; 
  }

  if(LDR_new < 650)
  {
   state = 0; 
  }

A simple else block would have taken care of the less than (or equal) 650 bit.

  if(state == 0)
  {
   digitalWrite(12, LOW);
  }
  
  if(state = 1);
  {
    digitalWrite(12, HIGH);
  }

Look at these two if statements. Can you see BOTH errors in the second one?

And the third error is that there shouldn't be an "if" there at all, just an "else" .

Of course!! Silly me! Thank you for your help, I've put in a 'else' as well :slight_smile:

, I've put in a 'else' as well

"as well" or "instead"?