≡ Menu

Motion and Light Sensors with Arduino (and Without)

I have recently received the following question from a reader:

I’m looking for a circuit board design that will need to turn on an array of LEDs when motion is detected during the day time, and also stay on continuously during the night time; using the Arduino would be nice. The project that I am working on is just a picture frame with my artwork in it. The art is actually an embossed piece. The light that I am placing within the frame will shine across the embossed art, and reflect off the raised areas of paper and make the picture appear more three-dimensional. So, the picture acts as a night light when it’s dark, and then turns on for a moment during the day time when some approaches the picture.

I suspected there had to be a simple circuit to accomplish this without having to program a microcontroller to take care of triggering the light. I could see that was overkill; after all, it is just a way to switch lights on/off. Still, I had no idea how to do it, if not from a software point of view.

Well, he mentioned the Arduino in his email, and I wanted to give him a quick response, so I put together a prototype to achieve the effect he desired. I properly warned him that might not be the best solution, but since he wanted to tinker with the Arduino, that would be a simple sketch.

I suggested the use of a compact Arduino clone like the Ardweeny (check out “Testing the Ardweeny” to see how tiny it is!)

Then, soldering everything onto a strip-board should result in a small footprint that would not detract from his art piece.

Anyway, here’s a Fritzing diagram that shows how to wire the circuit:

Fritzing diagram for Arduino PIR sensor and photocell

You can see the Arduino, LDR (light sensor, the component with the “squiggly” line), LED and PIR (motion sensor, the black “mystery” component to the right — the Fritzing version I’m using has no PIR component and I still don’t know how to add a custom component the proper way).

Here’s an excellent tutorial on the use of PIRs, from Ladyada who did create her own component on Fritzing.

And here’s a picture of the setup:

Motion and Light Sensors with Arduino circuit

Bill of Materials for the Motion and Light Sensors with Arduino

(includes parts used for both Arduino and non-Arduino* versions):

Here’s a video showing the concept:

And here’s the Arduino sketch:

/* www.TinkerHobby.com
 * Natalia Fargasch Norman
 * Motion detection using Arduino
 */

#define LDR 0
#define PIR 2
#define LED 3

int pirState;
int ldrValue;

void setup() {
  //Serial.begin(9600);
  pinMode(LED, OUTPUT);
  pinMode(PIR, INPUT);
  digitalWrite(LED, LOW);
}

void loop(){
  ldrValue = analogRead(LDR);
  //Serial.print("Analog reading = ");
  //Serial.println(ldrValue);

  if (ldrValue <= 512) { // dark
    digitalWrite(LED, HIGH);
  } 
  else { // ldrValue > 512
    pirState = digitalRead(PIR);
    if (pirState == HIGH) {
      digitalWrite(LED, HIGH);
      delay(5000);
      digitalWrite(LED, LOW);
      delay(1000);
    } 
    else { // pirState == LOW
      digitalWrite(LED, LOW);
    }
  }
  // The processing in the Arduino occurs faster
  // than the response from the PIR, and adding this delay
  // eliminated a flickering on the LED
  delay(1000);
}

The idea is to trigger the light when it’s dark; otherwise, trigger it for a short duration if motion is detected. This simple Arduino sketch does just that. A light dependent resistor is connected to an analog pin on the Arduino, and reading from it will either trigger the light (if it’s dark) or have the Arduino check for motion by reading from the motion sensor connected to a digital pin (if it’s not dark).

And finally… a non-Arduino version!

A few days and a couple of aha! moments later, I finally figured out how to accomplish the same behavior without using a microcontroller.

I knew an OR gate could be used to trigger the LED (output) on either (or both, doesn’t matter) condition: darkness or motion detected. The PIR outputs either 0 (no motion detected) or 1 (motion detected). But what about the light detection piece of the circuit? The LDR gives me an analog reading, and I needed a 0 or a 1 as inputs to the OR gate.

When later reading about transistors in Forrest Mims’ “Getting Started in Electronics” it occurred to me that I could use one as a switch on the LDR part of the circuit to generate the second input to the OR gate.

So I excitedly went to Marvac (my trusty local electronics shop) to buy OR gates; unfortunately, they were out of stock… 🙁

But then, again courtesy of Forrest Mims, I learned how to build my own OR gate using two rectifier diodes. (And I had the necessary parts!)

Here’s how it’s wired:

Diode OR Gate

Now on to the complete circuit…

First I hooked up the LED to the OR circuit to test that it worked. Check.

Then I connected the PIR to the LED to make sure that it woks, i.e. LED lights up when there is motion detected. Check.

Then I connected the PIR to be the first input of the OR gate… and it didn’t work.

I hooked up the LDR as the second input to the OR gate and that part… “kind of” worked. (LED off when dark and on when light; should be the other way around). I had used an NPN transistor, so I just switched to a PNP instead and it worked. Makes sense!

This is how it was hooked up: Emitter to ground, Collector to load (the LED) and Base to LDR. The LDR was connected to a 10K pull-up resistor and a potentiometer (to fine tune the amount of darkness it takes to trigger the LED).

But the PIR part of the circuit was still “kaputt”… I checked with the logic probe and found out that there was a signal coming to the LED. I replaced it with a diffused LED and could see that it was actually on, just veeeery faint.

Using a multimeter I measured the voltage between the LED leads and it was 2.3V. My power source was 4.92V. It seems that the PIR causes a voltage drop…

Then I looked at the datasheet for the Parallax PIR I have (note to self: that should definitely NOT be an afterthought), and learned that there are two versions, and that mine requires a transistor or a MOSFET to drive external loads.

I hooked up a random (I’m no EE!) transistor (a 2N2222) and now the LED is brighter. But still not as bright as when I cover the LDR.

Looking at the current values, my multimeter read:

Current through the LED when the LDR portion of the circuit is active: 4.2mA
Current through the LED when the PIR portion of the circuit is active: 0.8mA

The only other transistors I had were 2N3904, so I decided to try that one. The LED was much brighter and the current read 2.4mA. With a base current of 0.02mA I was getting a gain of 40 with the 2N2222 and 120 with the 2N3904.

I checked the datasheets for these two transistors, and these gain values were consistent. After some research it seems the BC548B is a better amplifier transistor for this application, and has a minimum gain of 200.

Here’s what the circuit looks like on Fritzing:

Fritzing diagram for motion-triggered light

And here’s a picture of the real thing:

Circuit for the motion-triggered light

By the way, I heard back from my reader; he bought the Boarduino from Adafruit, not the Ardweeny, and successfully built his “darkness-or-motion-triggered artwork illumination” project.

Keep sending me your questions; I love to see what you are working on, and it helps me on my learning journey as well. (Explaining something to somebody else is the best way to learn). I will also from time to time publish some of your questions here. (If you have an electronics blog let me know and I will include it here).

{ 54 comments… add one }
  • Natalia, i see an online group session class in our future starring you as professor electronic. Seriously this is amazing. To me, a non electronic hobbyist, this seems far more advanced than a hobbyist. Is this your day job too?
    I’ve always wanted to take apart one of catherines dolls that speak. it says something silly like “i love you”. I wanted to reprogram it so that i could put my own messages in it something more meaningful like “brush your teeth” and ” don’t talk back to mommy” and “be kind to your elders” . is that even posssible to take a store bought toy and do that? or does that require a slew of equipment and stuff i don’t have?

    • Annie, I used to work with software, but never with electronics. It would be possible to do something like that with a doll, but the vague idea I have on how to do this involves the doll having to wear a “purse” to carry her hardware with her… I don’t have experience with modding yet, but it is on my list of things to explore.

      • When we lived in California, the MakeFaire would come by once a year and we would always go there as a family. This seems like something they would have available there.

  • Interesting stuff. Thanks for sharing.

    I found this through doing a search for “LDR motion sensor”.

    I’m attempting to create a motion sensing device that only uses an LDR. I want to make a load of these things so using PIRs is going to be cost prohibitive.

    I’m researching OpAmps at the moment to increase the output from the LDR. Do you have any experience with OpAmps?

    I’ll be squirting the output to an Arduino – most likely an ATtiny85 pretending to be an Arduino – so a change of a few percent at the analog input, up or down, will trigger a response.

    kr Marcel

    • Hey Marcel,

      your project sounds interesting! It’s always interesting to see what can be done in order to lower the costs for a project. Sorry, I have no experience with OpAmps… (I actually even had to google it)…

      But good luck!

      • Thanks Natalia.

        hehe – googling is what I’ve been spending a lot of time doing!

        I ran an experiment yesterday into skipping the OpAmp bit and seeing what kind of result I get on an analog input on an Arduino. I’ve set the LDR up as half of a voltage divider and lo and behold… it works! I thought I’d need an OpAmp to get a useable signal.

        Tonight’s experiment will be to port it over to the ATtiny85 – as facilitated by those lovely people at MIT 🙂

        As you say, it lowers the cost and simplifies the whole thing. Is good.

        [m]

  • Shawn Shay

    Can you post the fritzing .fzz file?

  • Sam

    Hi Natalia…tried the project out and it works ok for the pir aspect,the ldr aspect keeps blinking anytime i turn my lights off…and what are the values of the resistors used in the arduino project am having a difficulty identifying them.

    • Hi Sam,

      if you look at the bill of materials I posted, the pull down resistor is 10K Ohm and the current limiting resistor is 180 Ohm. The current limiting resistance might be slightly different if you are using an LED of different specs (check the datasheet) but you can calculate the value using Ohm’s Law. Finally, is the LED you’re using a regular one, or a blinking one?

  • Sam

    Natalia,
    Thanks…I’m using a regular LED….but then, how do I get the LED to stay on for a few more seconds after motion/darkness has been sensed? ,that can be done right?

    • Hi Sam,

      did you take a look at the code I posted? The part starting at

      if (ldrValue <= 512) { // dark is the two conditions when the LED will turn on. This code keeps the LED on indefinitely if it remains dark, and for 5 seconds (the delay(5000) part) when motion is detected. As long as you do not set the LED pin to LOW, the LED will remain on. You can change the 5 seconds to any value you want, by adjusting the delay.

  • Darkknight

    Pls help me in my thesis my idea is a pir motion detector and i want it to alarm when it detect a motion but i want to make my device turn off automatically during day time and turn on automatically in night time using ldr..plss help

    • Hi,

      you should be able to create that using the same idea as above, but replacing the light with a piezo buzzer…

  • very good tutorial and I’m waiting new and innovative ways where light sensors are used in robotics applications

  • George

    Hi Natalia,
    I’m very new to all of this and am thinking of doing a similar script.
    I’d like to have a few leds turn on when motion in detected only at night. This would be the only time that they are on.
    From what I’ve read it seems like using a photocell is the easiest way to do this.
    How would I go about doing this?
    Or could you think of an easier way to do it?
    Thanks,
    George

    • Hi George,

      I understood you want to do something similar, but if there is motion when it is not dark you want to ignore it then, is this right?

      With my understanding, you would use the same components as I did (the PIR and the LDR) but instead of turning the lights on when PIR *OR* LDR HIGH, you would do PIR *AND* LDR HIGH.

      BTW sorry for the delay. I travel so often (too often in my opinion!) that sometimes I miss email notifications for comments…

      Take care,
      Natalia.

      • Divyansh

        Hey AND logic in non arduino circuit is not working !!! Can you post the AND logic circuit or just guide me for that …. and tell me about if i want to energize relay instead of led ON OFF

  • Abdallah

    nice work 🙂
    but if I want to use 2 PIR sensors in the door opening and count the amount of people who enter or leave the room. and when nobody at room the light swithes off ..what I will do ???

    • Thanks Abdallah!

      You will follow the same fashion as above, but will add a second PIR. They will be placed say, one at the very entrance (lets call it PIR1), and one a bit further from the entrance (let’s call it PIR2), inside the room. When they are triggered in the order PIR1 followed by PIR2, you increment the number of people in the room. When they are triggered in the order PIR2 followed by PIR2, you decrement the number of people in the room. If the number of people in the room is 0, then you turn off the lights.

      Hope this helps!
      Natalia.

      • Abdallah

        ok.. thanks a lot 🙂
        but can you help me to find the required code to apply this idea ??!

        • Well, you won’t find the exact code you need, unless someone has implemented the exact same idea as you, AND posted it on the Internet. 😉

          The biggest joy of tinkering is being able to figure things out, and the immense feeling of accomplishment once your project works…

          I suggest you try with what I mentioned above, which is very similar to my implementation, except you will be reading from the 2 PIRs. You will only need to add a counter variable to keep track of the number of people in the room. Assuming it starts out empty, you initialize it to 0, then increment it or decrement it in the fashion I described above, depending on the order the 2 PIRs are triggered.

  • Abdallah

    thanks a lot Natalia 🙂

  • Arshad

    Hi Natalia,

    Great work here!
    I followed exactly what you did but i seem to get only the LED to be just lightning up all the way. The LDR and sensor doesnt work!

    • Hi Arshad,

      thanks! What version did you try to implement? The one with, or without the Arduino?

      A couple of things to keep in mind that may help you debug is that the LDR should have a pull-up (or pull-down) resistor, and depending on the specs of your PIR, you may or may not need a transistor to amplify the output signal, like I did.

      The lighting of the LED is conditional, so you need to base that on the readings of the two sensors (the LDR and the PIR).

      Hope you can make it work!

  • Emil

    Hello Natalia.

    I really like you project.

    I trying to build something similar but instead of using a single led I would like to use an led strip. But the question is if I going to need any extra power supply to accomplish that?
    I will really appreciate your answer.
    Thanks.

    • Hi Emil,

      it depends. The Arduino can supply 3.3 V or 5 V, and the pins can source 40 mA. What are the requirements of your LED strip? If it operates under a higher voltage and/or sinks more than 40 mA, it will need its own power.

      • Emil

        Thank you for answer.

        The LED strip that Im using require 12V. I connected the LED stripe to the 12V transformer that came with the led and the other side I connected to the breadboard. The lights turn on but the intensity is to low.
        Now Im trying to find out how to resolve this issue. If you have any suggestion is going to be more than welcome.

        Thank you for your time,

        Emil

        • Hi Emil,

          I’m not sure what this transformer is that you are talking about. You need to connect the LED strip to an external power source, not the Arduino, as it can only supply 5V. Do you have a bench top power supply? I’d use that while testing.

  • Emil

    Thank you for answer.

    The LED strip that Im using require 12V. I connected the LED stripe to the 12V transformer that came with the led and the other side I connected to the breadboard. The lights turn on but the intensity is to low.
    Now Im trying to find out how to resolve this issue. If you have any suggestion is going to be more than welcome.

    Thank you for your time,

    Emil

  • dinh

    can you post the circuit diagram for non-arduino please

    • Hi Dinh,

      I don’t have a schematic, only the Fritzing screen capture above. It shows all the connections clearly, though, so you should have no problem hooking it up. Sorry, it’s on my to do list to go back to old posts and complete any missing information, such as schematics or bill of materials, etc. but I seem to (always) be buried under so many things calling for my attention!

      Do you think the Fritzing diagram can help you? Let me know. It is the second picture from bottom to top.

  • Jordan

    Hello, I’ve followed the steps that you have posted in this website but my LED light doesn’t seems to be turning off when there’s no motion. The light will always be on no matter what happen.

  • S.Ravikumar

    Sir can you send the circuit diagram for the digital counting devices using Passive Infrared Sensor and program for the counting purpose to mail id (raviraviravi2205@gmail.com)
    Thank you

  • syed zaker

    can u give me a circuit diagram with pir motion sensor

  • SRI

    Hye,
    Which transistor is used in non-Arduino circuit and that is NPN or PNP?
    My PIR sensor got only 3pin but urs sensor got 5 pin, it is same?

  • SRI

    Hye,
    Which transistor is used in non-Arduino circuit and that is NPN or PNP?

  • SRI

    How much Voltage need for non-Arduino circiut

  • Hi Natalia Nice to Meet you!

    I’m really interested about your article its really helpful, and we have same project by the way, i was search many website at google then finally i got your website, really really useful

    I saw your codes and i found delay 5 seconds when the motion detected (Led On), is the delay react to LED On for 5 seconds? if i changed the delay to 5 minutes did the LED On for 5 minutes? (i’m sorry if my english bad ehehheh)

    Thank You Before,

    Jefri

  • David

    Hi Natalia, Im using the same code and circuit that you have but my LED doesn’t turn off… Im using a parallax PIR Motion Sensor. Please help this is part of my final project and I need to get it done ASAP.

    Thanks,

    David

  • SHEIRA

    Hello Natalia.. Im doing this project for my final..I’ve tried your coding so many times..but still i could not make it.. i really follow what have u taught.. but its still not working.. plez help me 🙁

  • Ahmad Yusuf

    hi natalia, may i know your email? i wanna ask some quetions. i treid ur sketch but stil got an error. i made the lamp and cooler system using input an LM35, LDR and PIR. can u help me, please.

  • De Pooter Nico

    Hello,
    What would be the code if the LDR and PIR should be both active before the led triggers?
    Now it’s a code with if…else… but I need a kind of AND function before the led goes on.
    Thanks in advance,
    Regards Nico

  • Supriya

    Give me circuit diagram

  • Supriya

    Give me circuit diagram of dat circuit

  • Jimmy

    Hi Natalia,

    Great work here!
    I followed exactly what you did but i seem to get only the LED to be just lightning up all the way. The LDR and sensor doesn’t work! I’m using the arduino verison.

  • Divyansh

    Instead of OR logic i want to impliment AND logic ….
    I tried implimenting it by make and circuit but it din’t worked !!!
    And moreover if i want to energize the relay from output of the OR logic or AND logic … it is also not working !!! Please help me … thank you

    • Divyansh

      This post is in reference with non arduino circuit … please help me … how to overcome this issue

  • Edward

    Hi, can you please make Arduino and non Arduino project, same like this but to add sound clap switch sensor?

  • trisha

    HI NATALIA
    i am new to this and i need the exact same project although i would like to add a dimmer switch when it is night time user should hAve an extra benefit feature to dim lights

  • Felix C

    I was trying to sign up for your to your site but it wouldnt let me and get the arduino book is there anyway you can help.

    thanks

    FC

Leave a Comment