Loading...
Pages: [1]   Go Down
Author Topic: Changing a variable based on an analog sensor  (Read 171 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: 311
Posts: 35470
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: 137
Posts: 19008
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.

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: 137
Posts: 19008
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.

Pages: [1]   Go Up
Print
 
Jump to: