Pages: [1]   Go Down
Author Topic: Changing a variable based on an analog sensor  (Read 303 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 8
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.

Code:

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);
 
}

Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 549
Posts: 46107
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
  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.

Code:
  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?
Logged

Global Moderator
UK
Offline Offline
Brattain Member
*****
Karma: 238
Posts: 24370
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Offline Offline
Newbie
*
Karma: 0
Posts: 8
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Global Moderator
UK
Offline Offline
Brattain Member
*****
Karma: 238
Posts: 24370
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
, I've put in a 'else' as well
"as well" or "instead"?
Logged

"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Pages: [1]   Go Up
Jump to: