Page 1 of 1

Arduino – Playing with a light sensitive resistor (LDR)

Arduino – Playing with a light sensitive resistor (LDR)
   13

After building my own Ambient Light for my TV (Boblight project), several users asked how to control the light intensity of the LEDs based on the ambient light.

So the LEDs should be brighter during the day, and more dimm at night.

This brought me to explore the use of different light sensors on an Arduino, where the cheapest and most common one is a so called LDR (Light Dependent Resistor). An LDR decreases in it’s resistance as light increases.

Looking at what I could find online, I did find that there is enough information available when using an Analog pin of the Arduino. In this article however, we will also look at using a Digital pin to read an ON/OFF state. So in this article I’ll show you some of the basics on how to use an LDR with your Arduino.

In this article I’ll discuss both options.




Reading Ambient Light with an LDR

First thing we should know, is that an LDR (Light Dependent Resistor, or Photo resistor) is basically a resistor that change resistance depending on light. More light means less resistance. Less light means more resistance.

LDR’s have been around for a very long time (as a kid I already played with LDR’s) and cheap. Not to mention: pretty rugged and very cheap.

Now when connecting an LDR to you Arduino, one would automatically go for one of the Analog pins, but analog pins are slow when it comes to reading them. Therefor in this article, we will also show you how to connect them to be used with a Digital pin, which gives us an ON/OFF state instead of a value.

Measuring light and LDR 

Note that the phrase “measuring light” is not really what I would call this.
LDR’s are not a all that accurate way of measuring light as such.

It is however a great tool for detecting ambient light … roughly.

LDR on an Arduino Analog Pin

This would be the most used and most obvious way to use an LDR, as it fluctuates resistance, producing many values.

In this setup we will make it that the value read from the Analog pin will actually increase as light increases. For this we use a tiny circuit that pushes power through the LDR. Since the LDR decreases its resistance as light increases, more “power” will pass through it to the Analog pin, which results in the Arduino “reading” a higher value.

The analog pin will read values between 0 and 1023, so it converts the analog signal to a digital representation – also called Analog Digital Converter (AD or ADC), which is build into the Arduino.

All we need is:

  • Arduino (I used an Uno, clones as of late have been reported to be problematic at times)
  • USB cable to connect the Arduino to our computer
  • Arduino IDE (free download)
  • an LDR (duh!)
  • a 100KΩ resistor (brown-black-yellow, or see our Resistor Calculator)
  • 3 wires
  • a small breadboard

 

The setup is very simple:

In words:

Connect +5V of the Arduino to one pin of the LDR (LDR pins can be swapped, so no worries about polarity here).
Connect the other pin of the LDR to A0 (analog pin of the Arduino) and one pin of the 100KΩ resistor.
Connect the other pin of the 100KΩ resistor to GND of the Arduino.

Schematic (done with Fritzing):

Arduino - LDR connected to an Analog Pin

Arduino – LDR connected to an Analog Pin

Breadboard drawing (done with Fritzing):

Arduino - LDR connected to an Analog Pin

Arduino – LDR connected to an Analog Pin

The sketch is straight forward as well, and will display the read analog value through the serial port so we can see what is happening.


1
2
3
4
5
6
7
8
9
10
11
12
13
#define LDRpin A0 // pin where we connected the LDR and the resistor

int LDRValue = 0;     // result of reading the analog pin

void setup() {
  Serial.begin(9600); // sets serial port for communication
}

void loop() {
  LDRValue = analogRead(LDRpin); // read the value from the LDR
  Serial.println(LDRValue);      // print the value to the serial port
  delay(100);                    // wait a little
}

Connect your Arduino with the USB cable to your computer.

Start the Arduino IDE and make sure you select the right board and serial port.
For selecting the right board, go to “Tools”   Board”   Arduino Uno” (if you’re using an Arduino Uno), and for the right port, go to “Tools”   Port”   /dev/cu.usbmodem1411 (Arduino Uno)” (this is on my Mac, your Mac or PC might show something different).

Copy and past the sketch above into the Arduino IDE (either paste over the existing empty code, or open a new sketch – “File”   New“) and click the “Upload” button, which in the figure below is button “B“.

Arduino Software - Useful shortcuts

Arduino Software – Useful shortcuts

Next start the “Tools”   Serial Monitor” so we can see the output, which will be something like this:


...

949
945
943
917
838
837
832
796
748
709
706
704
692
689
698

...

Without doing anything, the value seems to hover around 917 … 950, moving my hand over the sensor however (limiting light) will make it drop below 800.

Note that these values will probably be different in your environment.
Play a little with it and see what the values do.

LDR on an Arduino Digital Pin

Now that we have seen the LDR work on an Analog pin, time to look at what will happen with a digital pin on your Arduino.

Keep in mind that the digital pin only returns a 1 or a 0 (zero), unlike the Analog pin, which is useful if something needs to be switched ON or OFF, like for example lights.

It seems that for an Arduino, a voltage threshold of 2.2 V triggers either 1 or 0. Also note that reading this value goes much faster than reading an Analog pin, which is crucial for applications where speed is of the essence (for example the Boblight application).
So lets test this.

For this purpose I will use a potentiometer, which is a variable resistor so I can fine tune when it’s light enough to go ON (1) and dark enough to go OFF (0). The main reason for this is that your ambient light (environment) will be different from mine. Not to mention: where ever you are going to apply this, might be in a darker or lighter place then where you’re building your Arduino setup.

We will use the same components as before, however we will replace the resistor with a potentiometer.

A potentiometer typically has 3 pins. The one in the middle is the variable dial and the ones on the left and right are basically a resistor. The variable dial slides over this resistor and “taps” off a resistance between zero and the max resistance of the resistor.

Maybe this drawing explains it better:

R is the “full” resistor. It has two pins: R1 and R2.
If you’d use a multimeter and measure the resistance between pins R1 and R2 then you’ve read the resistance of the resistor R.

The wiper (V) creates a “shortcut”, so if you’d measure the resistance between R1 and V, you’d only measure the resistance of R that is found between the pins R1 and V. Or if you’d measure the resistance between R2 and V, you’d be measuring the resistance of R between R2 and V.

So moving the wiper, would change the distance between, for example, R1 and V – the longer the distance between these two pins, the higher the resistance between the pins R1 and V. Makes sense?

In our setup we use only 2 of the 3 pins, the middle one and one on the right or left.

How a potentiometer works

How a potentiometer works

All we need is:

  • Arduino (I used an Uno, clones as of late have been reported to be problematic at times)
  • USB cable to connect the Arduino to our computer
  • Arduino IDE (free download)
  • an LDR (duh!)
  • a 10KΩ potentioneter (feel free to try higher or lower values)
  • 3 wires
  • a small breadboard

 

In words:

Connect +5V to one pin of the LDR (LDR pins can be swapped, so no worries about polarity here).
Connect the other pin of the LDR to Digital pin 8 (of the Arduino) and the outside pin of the 10KΩ potentiometer (either left or right).
Connect the middle pin of the 10KΩ potentiometer to GND of the Arduino.

The following drawings might look a lot different, but they really are not that different than the analog example.
We replace the 100KΩ resistor with a 10KΩ potentiometer, and instead of the Analog Pin A0, we use the Digital Pin 8.

Schematic (done with Fritzing):

Arduino - LDR connected to an Digital Pin

Arduino – LDR connected to an Digital Pin

Breadboard drawing (done with Fritzing):

Arduino - LDR connected to a Digital Pin

Arduino – LDR connected to a Digital Pin

The sketch is going to be almost the same as the one for the Analog method.
We only changed the fact that we read a digital signal from pin 8.


1
2
3
4
5
6
7
8
9
10
11
12
13
#define LDRpin 8  // pin where we connect LDR and resistor

int LDRValue = 0; // result of reading the analog pin

void setup() {
  Serial.begin(9600); // sets serial port for communication
}

void loop() {
  LDRValue = digitalRead(LDRpin);// read the value from the LDR
  Serial.println(LDRValue);      // print the value to the serial port
  delay(100);                    // wait a little
}

Connect your Arduino with the USB cable to your computer.

Start the Arduino IDE and make sure you select the right board and serial port.
For selecting the right board, go to “Tools”   Board”   Arduino Uno” (if you’re using an Arduino Uno),
And for the right port, go to “Tools”   Port”   /dev/cu.usbmodem1411 (Arduino Uno)” (this is on my Mac, your Mac or PC might show something different).

Copy and past the sketch above into the Arduino IDE (either paste over the existing empty code, or open a new sketch – “File”   New“) and click the “Upload” button.

Next start the “Tools”   Serial Monitor” so we can see the output, which will be something like this:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1
1
1
1
1
1
1
1
1
1
1
1
1
1

This could also be a load of zero’s.

Now gently turn the knob of the potentiometer until it switches values. So if you started with a lot of  1’s, turn slowly until they become zero’s or the other way around. Do not turn that knob too fast, you’ll have to look for the sweet spot where it switches output value.

Once you have found the sweet spot, hold you hand over the LDR and you’ll see it change. If not: tune that potentiometer a little more until it does.

LDR on an Arduino Digital Pin Expanded

Now, with one LDR on a digital pin, we can only read an ON and OFF state, which might not be all that great if you want more than 2 intervals (range OFF and range ON).

Say we’d like to 3 light levels, then 2 LDR’s on each their own digital pins might do the trick – all under the assumption that reading analog pins is too slow of course. Below an example how this can be done. You can expand this idea with as many LDR’s as you like and your Arduino can handle.

Basically what we do is make one LDR switch to ON quicker than the other LDR. For that purpose they both have their own potentiometer so we can tune them as we see fit for each “level”.

For the second LDR we use pin 7 (in the Sketch) – feel free to use another pin, but make sure to adjust the sketch accordingly.

Schematic (done with Fritzing):

Arduino - Double LDR connected to an Digital Pin

Arduino – Double LDR connected to an Digital Pin

Breadboard drawing (done with Fritzing):

Arduino - Double LDR connected to an Digital Pin

Arduino – Double LDR connected to an Digital Pin

The sketch fort this setup:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#define LDRpin1 7  // pin where we connect LDR and resistor
#define LDRpin2 8  // pin where we connect LDR and resistor

int LDRValue1 = 0; // result of reading the digital pin
int LDRValue2 = 0; // result of reading the digital pin

void setup() {
  Serial.begin(9600); // sets serial port for communication
}

void loop() {
  LDRValue1 = digitalRead(LDRpin1);// read the value from the LDR
  LDRValue2 = digitalRead(LDRpin2);// read the value from the LDR
 
  Serial.print(LDRValue1);         // print the LDR1 value to the serial port
  Serial.print(" ");               // print a space
  Serial.println(LDRValue2);       // print the LDR2 value to the serial port
 
  delay(100);                    // wait a little
}

Depending on the potentiometer settings and your ambient light you will see sets of “0 0”, “1 0”, “0 1” or “1 1” flying by.
First turn both potentionmeters to one far end.

Setting the “low” level:
Turn down your ambient light until the point that you consider “dark”.
Turn both potentiometers until you only see sets of “0 0”. This will be our “dark” level.

Setting the “medium” level:
Set your ambient light to what you’d consider “medium”.
Very slowly turn up only one of the potentiometers, let’s say LDR1, until sets “1 0” start appearing.
(if you’d do this with LDR2 instead, sets of “0 1” should appear)

Setting the “high” level:
Now crank up the ambient light to what you’d consider “high” (anything brighter will be consider “high” as well).
Very slowly move up the potentiometer of LDR2 until sets of “1 1” start appearing.

Play a little with this and you’ll get the hang of the fine tuning part.

The following example code gives you an idea what you could do with this:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#define LDRpin1 7  // pin where we connect LDR and resistor
#define LDRpin2 8  // pin where we connect LDR and resistor

int LDRValue1 = 0; // result of reading the digital pin
int LDRValue2 = 0; // result of reading the digital pin

void setup() {
  Serial.begin(9600); // sets serial port for communication
}

void loop() {
  LDRValue1 = digitalRead(LDRpin1);// read the value from the LDR
  LDRValue2 = digitalRead(LDRpin2);// read the value from the LDR
 
  Serial.print(LDRValue1);         // print the LDR1 value to the serial port
  Serial.print(" ");               // print a space
  Serial.print(LDRValue2);         // print the LDR2 value to the serial port
 
  if((LDRValue1==1)&&(LDRValue2==1)) {
    Serial.print(" -> HIGH"); }
  else if ((LDRValue1==1)&&(LDRValue2==0)) {
    Serial.print(" -> MEDIUM"); }
  else if ((LDRValue1==0)&&(LDRValue2==0)) {
    Serial.print(" -> LOW"); }
   
  Serial.println(" lighting");
 
  delay(100);                    // wait a little
}

Output example (in a darker room, while slowly moving a flashlight towards both LDRs) could look like this after tuning the potentiometers:


1
2
3
4
5
6
7
8
9
10
11
12
0 0 -> LOW lighting
0 0 -> LOW lighting
0 0 -> LOW lighting
0 0 -> LOW lighting
0 0 -> LOW lighting
1 0 -> MEDIUM lighting
1 0 -> MEDIUM lighting
1 0 -> MEDIUM lighting
1 0 -> MEDIUM lighting
1 1 -> HIGH lighting
1 1 -> HIGH lighting
1 1 -> HIGH lighting

To apply this in, for example, the Boblight project (untested), you could try something like the code below.
It’s just an example and to make comparing easier, I’ve added both LDRValue where I multiplied the second LDRvalue with 10.
So we get theoretically could get results like 0, 1, 10 and 11. As mentioned before, due to the overlap one value (10) will not occur, so we have { 0, 1, 11 } as possible outcomes.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#define LDRpin1 7  // pin where we connect LDR and resistor
#define LDRpin2 8  // pin where we connect LDR and resistor

...  // some other code of your project

void loop() {
  ... // your project loop

  AdjustBrightness();

  ... // More optional project code
}

void AdjustBrightness() {
  int LDRValue = 0; // result of reading the digital pin
 
  LDRValue = digitalRead(LDRpin1);// read the value from the LDR
  LDRValue = LDRValue + (digitalRead(LDRpin2)*10);// Add the value from the next LDR
 
  if(LDRValue==0) {
    // Dark, so set LED brightness for example to 50%
  }
  else if(LDRValue==10 {
    // Medium, so set LED brightness for example to 70%
  }
  else if(LDRValue==11) {
    // Bright light, set LED brightness for example to 100%
  }
}

 

Conclusion

With an LDR we can read ambient light, even though it’s not 100% accurate and suitable for measuring. It’s more of a detection tool for ambient light.

We can use an Analog pin or a Digital pin, each with it’s own purpose and application.

The use of the Analog pin gives you a range of 0 … 1023 for the measured results.
Measuring like this gives you a range to work with, but is relatively slow and in certain situations (Boblight for example), this will not be fast enough for practical use.

The Digital Pin approach is much faster and could be expanded by adding another LDR on a second pin and fine tune the potentiometer of that second LDR to a different sensitivity, so that in essence you could have 3 “values” or light levels … (there will be an overlap, so the 4th value would not occur)

Donation options


Donations are very much appreciated, but not required. Donations will be used for web-hosting expenses, project hardware or a motivational boost (a drink or snack). Thank you very much for those have donated already! It's truly AwEsOmE to see that folks like our articles and small applications.

Comments


There are 13 comments. You can read them below.
You can post your own comments by using the form below, or reply to existing comments by using the "Reply" button.

  • Nov 5, 2015 - 4:46 AM - izeman Comment Link

    this is my working code for one LDR with digital output.

    /* t4a_boblight
     * (C) 2014 Hans Luijten, www.tweaking4all.com
     *
     * t4a_boblight is free software and can be distributed and/or modified
     * freely as long as the copyright notice remains in place.
     * Nobody is allowed to charge you for this code.
     * Use of this code is entirely at your own risk.
     */
    #include "Adafruit_NeoPixel.h"
    // DEFINITIONS
    #define STARTCOLOR 0x0000AA // LED colors at start
    #define BLACK 0x000000 // LED color BLACK
    #define DATAPIN 13 // Datapin
    #define LEDCOUNT 248 // Number of LEDs used for boblight
    #define SHOWDELAY 200 // Delay in micro seconds before showing
    #define BAUDRATE 115200 // Serial port speed, 460800 tested with Arduino Uno R3
    // #define BRIGHTNESS 70 // Max. brightness in %
    #define LDRpin 11 // pin where we connect LDR and resistor
    const char prefix[] = {0x41, 0x64, 0x61, 0x00, 0x18, 0x4D}; // Start prefix
    char buffer[sizeof(prefix)]; // Temp buffer for receiving prefix data 
    // Init LED strand, WS2811/WS2912 specific
    // These might work for other configurations:
    // NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
    // NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
    // NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
    // NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDCOUNT, DATAPIN, NEO_GRB + NEO_KHZ800);
    int state; // Define current state
    #define STATE_WAITING 1 // - Waiting for prefix
    #define STATE_DO_PREFIX 2 // - Processing prefix
    #define STATE_DO_DATA 3 // - Handling incoming LED colors
    int readSerial; // Read Serial data (1)
    int currentLED; // Needed for assigning the color to the right LED
    int BRIGHTNESS = 90; // make sure this stays within 0...100
    void setup()
    {
      strip.begin(); // Init LED strand, set all black, then all to startcolor
      
      strip.setBrightness( (255 / 100) * BRIGHTNESS );
      
      setAllLEDs(BLACK, 0);
      setAllLEDs(STARTCOLOR, 5);
      
      Serial.begin(BAUDRATE); // Init serial speed
      
      state = STATE_WAITING; // Initial state: Waiting for prefix
    }

    void loop()
    {
     
      switch(state)
      {
        case STATE_WAITING: // *** Waiting for prefix ***
          if( Serial.available()>0 )
          {
            readSerial = Serial.read(); // Read one character
            
            if ( readSerial == prefix[0] ) // if this character is 1st prefix char
              { state = STATE_DO_PREFIX; } // then set state to handle prefix
          }
          break;
          
          
        case STATE_DO_PREFIX: // *** Processing Prefix ***
          if( Serial.available() > sizeof(prefix) - 2 ) 
          {
              Serial.readBytes(buffer, sizeof(prefix) - 1);
              
              for( int Counter = 0; Counter < sizeof(prefix) - 1; Counter++) 
              {
                if( buffer[Counter] == prefix[Counter+1] ) 
                {
                  state = STATE_DO_DATA; // Received character is in prefix, continue
                  currentLED = 0; // Set current LED to the first one
                }
                else 
                {
                  state = STATE_WAITING; // Crap, one of the received chars is NOT in the prefix
                  break; // Exit, to go back to waiting for the prefix
                } // end if buffer
              } // end for Counter
          } // end if Serial
          break;
          
          
        case STATE_DO_DATA: // *** Process incoming color data ***
          if( Serial.available() > 2 ) // if we receive more than 2 chars
          {
            Serial.readBytes( buffer, 3 ); // Abuse buffer to temp store 3 charaters
            strip.setPixelColor( currentLED++, buffer[0], buffer[1], buffer[2]); // and assing to LEDs
          }
      
          if( currentLED > LEDCOUNT ) // Reached the last LED? Display it!
          {
              strip.show(); // Make colors visible
              delayMicroseconds(SHOWDELAY); // Wait a few micro seconds
              
              state = STATE_WAITING; // Reset to waiting ...
              currentLED = 0; // and go to LED one
              
              break; // and exit ... and do it all over again
          }
          break; 
      } // switch(state)
     strip.setBrightness( (255 / 100) * BRIGHTNESS );
     AdjustBrightness();
    } // loop

    // Sets the color of all LEDs in the strand to 'color'
    // If 'wait'>0 then it will show a swipe from start to end
    void setAllLEDs(uint32_t color, int wait)
    {
      for ( int Counter=0; Counter < LEDCOUNT; Counter++ ) // For each LED
      {
        strip.setPixelColor( Counter, color ); // .. set the color
        if( wait > 0 ) // if a wait time was set then
        {
          strip.show(); // Show the LED color
          delay(wait); // and wait before we do the next LED
        } // if wait
        
      } // for Counter
      
      strip.show(); // Show all LEDs
    } // setAllLEDs
    void AdjustBrightness() {
      int LDRValue = 0; // result of reading the digital pin
      
      LDRValue = digitalRead(LDRpin);// read the value from the LDR
      
      if(LDRValue==0) { 
        BRIGHTNESS = 100;
        // Light, so set LED brightness to 100%
      }
      else { 
        BRIGHTNESS = 80;
        // Dark, so set LED brightness to 80%
      }
    }
    Reply

    izeman

    • Nov 5, 2015 - 4:53 AM - hans - Author: Comment Link

      Cool – does it work as you’d hoped it would work?

      Reply

      hans

      • Nov 5, 2015 - 8:48 AM - izeman Comment Link

        it works EXACTLY i was expecting it to work. well – with only TWO states of course. so no continous adjustment of brightness, but it’s a beginning. :)

        Reply

        izeman

      • Nov 5, 2015 - 9:13 AM - hans - Author: Comment Link

        Awesome!!! 

        Reply

        hans

    • Mar 4, 2017 - 9:48 AM - Amirul syafiq Comment Link

      how to use LDR without delay .. if LDR can light dark light .. .. when LDR is not light. bright lights

      Reply

      Amirul syafiq

      • Mar 4, 2017 - 11:40 AM - hans - Author: Comment Link

        Hi Amirul,

        I’m not quite sure what you’re asking?
        You mean how to use the LDR without Arduino? Or to control a light through the Arduino, depending on ambient light brightness?

        Reply

        hans

  • Jan 11, 2016 - 2:52 AM - Michal Comment Link

    hello guys, i want use LDR on digital pin as i want only complete ON/OFF ambilight. I have pi2+hyperion+WS2812b freshly build setup. I want it to be OFF while some amout of light “daylight” as i find it usefull in very bright light. and when dusk come turn ambilight ON ( i have set permanent 70% brightness). Can you please be so kind and help me with this?it shouldnt be difficult to do for you :)

    one more question- if im wathcing TV in bright light and ambilight is OFF dark come will it automatically turn ON or i need reboot my kodi for it to turn on?

    thanks a lot!

    Reply

    Michal

    • Jan 11, 2016 - 3:31 AM - izeman Comment Link

      i will point you in the right direction. i guess finding the solution is quite obvious then :)

      a hint: take a closer look on the second half of the code:

          BRIGHTNESS = 100;
          // Light, so set LED brightness to 100%
        }
        else { 
          BRIGHTNESS = 80;
          // Dark, so set LED brightness to 80%
      Reply

      izeman

    • Jan 11, 2016 - 4:23 AM - hans - Author: Comment Link

      Hi Michal!

      (and thanks IzeMan!!!)

      A related forum topic should get you started:

      Add ambient light detection

      It’s the reverse of what you want, but it will get you started,… 

      Reply

      hans

  • Jan 11, 2016 - 5:28 AM - Michal Comment Link
    #define LDRpin 11 // pin where we connect LDR and resistor
    .
    int BRIGHTNESS = 70; // make sure this stays within 0...100
    .
    .
    void AdjustBrightness() {
      int LDRValue = 0; // result of reading the digital pin
      
      LDRValue = digitalRead(LDRpin);// read the value from the LDR
      
      if(LDRValue==0) { 
        BRIGHTNESS = 0;
        // Light, so turn LEDs OFF 0% Brightness
      }
      else { 
        BRIGHTNESS = 70;
        // Dark, so set LED brightness to 70%
      }

    thanks guys!

    I did this. can it possibly work as i want it to?
    Is best way to turn off ambilight just set brightness to 0% ?

    will it need reboot arduino to refresh state? in that case ist not very efficient.

    Reply

    Michal

    • Jan 11, 2016 - 5:46 AM - hans - Author: Comment Link

      Hi Michal,

      that looks about right (can’t test it at this time), and if you call “AdjustBrightness()” in the “loop()”, it should automatically adjust, no reboot needed. Unless this functions slows down your Arduino too much and you only call it once in “setup()” – in that case a restart of the Arduino might be needed.

      Reply

      hans

  • Apr 28, 2016 - 5:25 PM - leo Comment Link

    and if I want to make a counter with 2 ldr, Example when the sensor1 is active, that means the person is in front of the door. Sensor1 active but the sensor2 is till inactive, when the person is through the door the sensor2 become active as sensor1. When the person moves forward the sensor1 become inactive but the sensor 2 is still active until the person moves from the door then sensor2 become inactive that means the person entre, otherwise if sensor1was active and then inactive before the sensor2 become active or the sensor2 become inactive in the same time as sensor1 that means the operation was cancelled.My email 

    Reply

    leo

    • Apr 29, 2016 - 4:01 AM - hans - Author: Comment Link

      Hi Leo,

      sounds like you like to “hand-over” the detection.
      So start with LDR1 active, if LDR2 becomes active as well, then LDR2 is the only active one. Something like that?

      I’d start by detection both sensors at the same time, and program your logic based on the results of either sensor.

      Something like:

      #define LDRpin1 7  // pin where we connect LDR 1 and resistor
      #define LDRpin2 8 // pin where we connect LDR 2 and resistor
      ... // some other code of your project 
      void loop() {
        ... // your project loop
        DoSomething();
        ... // More optional project code
      }
      void DoSomething() {
        int LDR1Value = 0; // result of reading the digital pin
        int LDR2Value = 0;
        LDR1Value = digitalRead(LDRpin1);// read the value from the LDR
        LDR2Value = digitalRead(LDRpin2);   
        if(LDR1Value==0) { 
          // do something   }
        else if(LDR2Value==0 {
          // do something 
        }
        else if( (LDR1Value==0)&&(LDR2Value==0) {
          // do something
        }
      }

      Obviously, the values tested is something you should try and find out which values work.
      However, for detecting a person (day or night), a PIR might work better, which would work with Arduino as well and eliminates the light sensitivity, and detects motion instead.

      Reply

      hans



Your Comment …

Friendly request to not post large files here (like source codes, log files or config files). Please use the Forum for that purpose.

Please share:
*
*
Notify me about new comments (email).
       You can also use your RSS reader to track comments.


Tweaking4All uses the free Gravatar service for Avatar display.
Tweaking4All will never share your email address with others.