Find all your DIY electronics in the MakerShed. 3D Printing, Kits, Arduino, Raspberry Pi, Books & more!

Make: Projects

PIR Sensor Arduino Alarm

Build a motion-sensing alarm with a PIR sensor and an Arduino microcontroller.

PIR Sensor Arduino Alarm

In this simple project, we’ll build a motion-sensing alarm using a PIR (passive infrared) sensor and an Arduino microcontroller. This is a great way to learn the basics of using digital input (from the sensor) and output (in this case, to a noisy buzzer) on your Arduino.

This alarm is handy for booby traps and practical jokes, and it’s just what you’ll need to detect a zombie invasion! Plus, it’s all built on a breadboard, so no soldering required!

Download the project code here.

Steps

Step #1: Gather your parts.

PrevNext
PIR Sensor Arduino Alarm

This project requires just a few parts, and because you\'re using a solderless breadboard and pre-cut jumper wires, you won\'t need any tools at all — except your computer and USB cable to connect the Arduino.

Step #2: Wire the Arduino to the breadboard.

PrevNext
PIR Sensor Arduino Alarm
  • Connect digital input/output (I/O) pin 2 on the Arduino to row 1 on the breadboard.
  • Connect the 5V pin on the Arduino to row 2 on the breadboard, and connect a nearby ground (Gnd) pin to row 3.

Step #3: Connect your motion sensor.

PrevNext
PIR Sensor Arduino AlarmPIR Sensor Arduino AlarmPIR Sensor Arduino AlarmPIR Sensor Arduino Alarm
  • Find the Gnd (–), Vcc (+), and Out pins on the PIR sensor.
  • Plug the PIR sensor into the breadboard so that its (–) pin connects to the Gnd row, its (+) pin connects to 5V, and its Out pin connects to digital pin 2.
  • NOTE: If you have a different sensor than the one shown here, you may need to extend the sensor's pins with a stacking female header, wires, interconnect cables, etc. to fit.

Step #4: Plug in the LED.

PrevNext
PIR Sensor Arduino AlarmPIR Sensor Arduino AlarmPIR Sensor Arduino Alarm
  • Plug the LED's anode (the longer leg) into digital pin 13 on the Arduino.
  • Plug the LED's cathode (the shorter leg, and/or the leg on the flattened side of the LED base) into the adjacent ground (Gnd) pin on the Arduino.

Step #5: Connect the piezo buzzer.

PrevNext
PIR Sensor Arduino AlarmPIR Sensor Arduino AlarmPIR Sensor Arduino Alarm
  • Connect the buzzer's red wire to the Arduino's digital pin 10.
  • Connect the buzzer's black wire to the Arduino's Gnd pin (there's a spare one on the Power block of pins).
  • NOTE: These two wires can be reversed, as the polarity of the buzzer doesn't matter.

Step #6: Program the Arduino.

PrevNext
PIR Sensor Arduino AlarmPIR Sensor Arduino AlarmPIR Sensor Arduino Alarm
  • Launch the Arduino IDE software. You can download it for free here.
  • Plug the USB cable into your computer and Arduino.
  • Set the board and port settings for your Arduino board, in this case, an Arduino Uno.
  • Open the PIR Alarm sketch found at this link: https://raw.github.com/jedgarpark/Make_PIR_Sensor/master/MAKE_PIR_Sensor.pde (Arduino programs are called sketches.)
  • Upload the sketch to the Arduino.

Step #7: Test your alarm.

PrevNext
PIR Sensor Arduino AlarmPIR Sensor Arduino AlarmPIR Sensor Arduino Alarm
  • When you power up your alarm, the PIR sensor will glow an ominous red. Stand very still or leave the room while the alarm calibrates the infrared level reading for the room.
  • Now test it by moving: the buzzer will buzz and the LED will light up.
  • Be amazed! Your PIR Sensor Arduino Alarm can sense movement up to 20 feet away. No one will be stealing your yo-yo today.
  • NOTE: Might not be reliable for detecting the undead.

Comments

  1. Goli Mohammadi says:

    It’s a PDF under Files at the top of the project. Have fun!

    1. sanderny says:

      If you have the code then send me on this address email “mf93@live.it” please!!

    2. Ethan Loewen says:

      where is the code. Plz HURRY

        1. Mr.MIx says:

          i tried downloading the sketch and its no where to be found…anyone know. this is probably something simple, right? yea whatever….

  2. John Edgar Park says:

    Brandon, sorry for the huge delay, I didn’t see your comment until now. You can change the delay time upon startup to be longer if you need. Try adding a new line as the first one in the void setup that reads: delay(5000);
    That’ll give you five seconds before it begins.

  3. Jeremy dePrisco says:

    I noticed when I took the code from the PDF, the formatting was off when it is copy/pasted into Arduino editor. Best to download the PDE which is on the right side of the page above.

  4. Nikko Canlas says:

    Hi! Nice project! wanna try it too.. but the thing is, I don’t know where to download the code.. I can’t find it….. :(

  5. eder says:

    “Were Is The Code I Can’t Find It”?

  6. John Edgar Park says:

    Sorry about that, we’re looking into what happened. It seems when the new formatting was introduced the code was no longer included.

  7. louis 0208 says:

    Hi, nice project, im looking to do an attack sensor so its very similar to this, my components are fairly simialar, just wanted to know will they work if swtiched with the ones in the project youve used, im using a vibrations motor as the output, and a sharp PIR sensor for the input, any help or advice will be great and really appreciated.

  8. Robert says:

    Hello, please send me the program?
    e-mail: robert-1406@hotmail.com

  9. Blake says:

    The Sketch seems to have been removed from the page. Does anyone know where? I even did a search for “pdf” in the source code of this page without a result (sorry Goli Mohammadi).

  10. Ivan says:

    Is there code for this yet?

  11. Elany says:

    Hello, send me the code? Please.
    elany7@gmail.com

  12. Mr.MIx says:

    cant download this pir sensor sketch, whats the deal? someone let me know just how much of an idiot iam?

  13. John Edgar Park says:

    Sorry for the delay in fixing the post. Here is the code, I’ll see about having it properly added to the project next.

    // Uses a PIR sensor to detect movement, buzzes a buzzer
    // more info here: http://blog.makezine.com/projects/pir-sensor-arduino-alarm/
    // email me, John Park, at jp@jpixl.net
    // based upon:
    // PIR sensor tester by Limor Fried of Adafruit
    // tone code by michael@thegrebs.com

    int ledPin = 13; // choose the pin for the LED
    int inputPin = 2; // choose the input pin (for PIR sensor)
    int pirState = LOW; // we start, assuming no motion detected
    int val = 0; // variable for reading the pin status
    int pinSpeaker = 10; //Set up a speaker on a PWM pin (digital 9, 10, or 11)

    void setup() {
    pinMode(ledPin, OUTPUT); // declare LED as output
    pinMode(inputPin, INPUT); // declare sensor as input
    pinMode(pinSpeaker, OUTPUT);
    Serial.begin(9600);
    }

    void loop(){
    val = digitalRead(inputPin); // read input value
    if (val == HIGH) { // check if the input is HIGH
    digitalWrite(ledPin, HIGH); // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
    // we have just turned on
    Serial.println(“Motion detected!”);
    // We only want to print on the output change, not state
    pirState = HIGH;
    }
    } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    playTone(0, 0);
    delay(300);
    if (pirState == HIGH){
    // we have just turned of
    Serial.println(“Motion ended!”);
    // We only want to print on the output change, not state
    pirState = LOW;
    }
    }
    }
    // duration in mSecs, frequency in hertz
    void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
    digitalWrite(pinSpeaker,HIGH);
    delayMicroseconds(period / 2);
    digitalWrite(pinSpeaker, LOW);
    delayMicroseconds(period / 2);
    elapsed_time += (period);
    }
    }

  14. JesstheBess says:

    Would it be possible to just run this off a battery?

    1. John Edgar Park says:

      Yes, you could run this off of batteries. I’ve done so and it works fine. I usually use 4 AA NiMH batteries.

  15. Arjun patel says:

    can you give me pir for 8051 controller

  16. Dave says:

    Thanks this is simple and neat. My nine year old son wanted to “invent” a device that scared off the birds under our deck so they didn’t make nests. So we used these plans. Going to try an add a camera to snap pics of it scaring off birds. Though knowing these birds they’ll just make a nest on top of it.

    1. John Edgar Park says:

      Excellent, did you and your son build the Duck Alarm?

  17. Ayupchap says:

    Hi, I seem to have trouble running the code it says “Cannot find anything named LOW” I have copied the code over, any idea what might be wrong?

    1. Ayupchap says:

      Scrap that, I worked out whats wrong. Essentially I am an idiot, I had opened the code up in Processing and not Arduino. Can someone tell me how to add a Camera to take photos to this please?

      1. John Edgar Park says:

        One straightforward way would be to use a camera that has an input for a remote switch, and have the Arduino close that for you with a transistor or relay. I made my own release switch: http://blog.makezine.com/2010/11/10/john-edgar-park-has-a-trigger-mouth/ using a 2.5mm phone earbud, you’d trigger it with the Arduino instead of the arcade button.

  18. TommyTDesign says:

    Great project!

    I was wondering if anyone could help me tweak the arduino sketch?

    What code could I insert to make it so that there is a 3 second delay between the PIR receiving a signal and the outputs?

    1. Brian says:

      There are other ways to make a delay, but the block of code using the Timer library allows for other actions to take place by using pulses to define your time-domain. If you use a Delay function that locks up the MCU until the delay is completed. You can find details at: http://playground.arduino.cc/Code/Timer

  19. Vidhi Shah says:

    Hey, is there a way to attach a servo instead? And what changes should be made to the code for that?

  20. metamorp says:

    what code if i use pir and keypad,
    keypad for on/of that sensor

  21. Ted says:

    My LED on pin 13 wont turn on, the PIR works fine, the only difference is I’m using a Duemilanove, any ideas.

  22. Blake says:

    This was a fun build to learn a little about the motion sensor. However, it is just not loud enough to keep the dogs from getting up on the table. :-(

    What I need is a simple circuit to boost the output signal to drive one of the Radio Shack sirens (9-12 volt). Or a modification that turns the output into a simple switch to turn on a separately powered 9 volt circuit connected to the siren.

    I have tried a couple of ideas from Hack a Week and Instructables but no success yet. How about a little help?

  23. Ronaldo Panaligan says:

    It may not Compile, the only error is you may have to retype the this character (“motion detected”) and (“motion ended”). It has to do with the way these character shows up on the internet. Thanks I’m going to try it now.

  24. Alex says:

    Do you have the Electrical Schematic for this configuration?

  25. GOOD DAY SIR i use RE200B pir sensor and the buzzer and the led is blingking and the buzzer is continuesly sounds up ….. is there a problem if i dont use the kind of pir that you use sir > ? help me please ..

    are RE200B AND YOUR PIR SENSOR THE SAME ?

  26. Sandy says:

    Sir I want Source code in ASM Language will you please help me.

  27. Zoey says:

    Hi..do you have block diagram for this project?

  28. Ben says:

    Hi nice post!
    I’m looking for a PIR sensor that its delay time is less than 5 seconds.
    Do you know one that can answer my needs?
    Thanks
    Ben

  29. priyanka saini says:

    hie nice project… i need arduino software… pls give me dat site

    1. priyanka saini says:

      i juz got :)

  30. Dombo says:

    Great tutoriol….!!!!!!
    I have search the web for asolution to switch with a pir my bedledlight on and off. And this great.
    Can you please tell me how i can change the buzzer code in to a ction to open the mosfet…
    Or a signal where the powerr on is for x seconds,please..

    Or can i set the mosfet to pin 13?

  31. HuDa Affandi says:

    sorry..how if i want when the PIR sensor detect the motion,then it will send the message via old cellphone to another cellphone to tell that the motion is detected..

  32. alex says:

    How can you change the duration of the buzzer?

  33. […] Um bom exemplo é o projeto de um alarme disparado por movimento que utiliza um destes sensores passivos de infravermelho, ou PIR – passive infrared – como são conhecidos no meio técnico. Estes sensores PIR são aqueles utilizados para acender as luzes do hall do elevador quando tem alguém por ali. Basicamente o sensor mede a quantidade de radiação infravermelha naquele ambiente. Como todo objeto que está com a temperatura acima do zero absoluto emite radiação infravermelho, quando alguém entra no hall o sensor percebe uma mudança na radiação naquele lugar e dispara o circuito para acender a lâmpada por um determinado período. No projeto em questão, a idéia é usar um destes sensores ligados a um Arduino para disparar um sinal sonoro quando uma mudança for detectada pelo sensor. Trata-se de um projeto bem simples, mas que é um bom começo para você se familiarizar com os conceitos de entradas e saídas da plataforma Arduino. Veja instruções detalhadas aqui. […]

  34. mlemos says:

    Hi, I’m writing a blog post about cool Arduino based projects and your’s is going to be there. Do you allow me to use one or two of your pictures in the post? I’m linking the references to the project back to this page.

    Thanks in advance!

    Manoel Lemos

    1. Dombo says:

      Please some one make my day….
      My Pir A is working only Pir B not.
      Where do i go wrong…

      // Twee pirren onder het bed...
      // Pir A en Pir B 
      //Pir B werkt niet...
       
      int ledPin = 12;                // choose the pin for the LED
      int inputPin = 2;               // choose the input pin (for PIR sensor)
      int inputPinB = 3;               // PIRB
      int pirState = LOW;             // we start, assuming no motion detected
      int pirStateB = LOW;             // PIR B
      int val = 1;                    // variable for reading the pin status
      int valB = 1;                    // PIR B
      void setup() {
        pinMode(ledPin, OUTPUT);      // declare LED as output
        pinMode(inputPin, INPUT);     // declare sensor as input
        pinMode(inputPinB, INPUT);     // PIr B
        Serial.begin(9600);
      }
      //////////////// PIR A
      void loop(){
        val = digitalRead(inputPin);  // read input value
         if (val == LOW) {            // Zorgt dat hij de goed "richting"op gaat High is de pir anders om
         digitalWrite(ledPin, HIGH);  // turn LED ON
           delay(100);        // uitlezen van ?
       ////////////////   
          if (pirState == HIGH) {      // 
           Serial.println("Motion detected!");      // 
            pirState = LOW;
            delay(100); // weet niet maar zal iets met uitlezen zijn.
       ///////////////////////////
            }
        } else {     digitalWrite(ledPin, LOW); // 
                   
          if (pirState == LOW){      // we have just turned of
          Serial.println("Motion ended!");      // 
          pirState = HIGH;
           delay(10000);  // Tijd lamp aan is
          }
        }
      } 
      /////////////////////
      
      //}
      ////////////////PIR B
      void loopB(){
        valB = digitalRead(inputPinB);  // read input value
         if (valB == LOW) {            // Zorgt dat hij de goed "richting"op gaat High is de pir anders om
         digitalWrite(ledPin, HIGH);  // turn LED ON
           delay(100);        // uitlezen van ?
       ////////////////   
          if (pirStateB == HIGH) {      // 
           Serial.println("Motion detected!");      // 
            pirStateB = LOW;
            delay(100); // weet niet maar zal iets met uitlezen zijn.
       ///////////////////////////
            }
        } else {     digitalWrite(ledPin, LOW); // 
                   
          if (pirStateB == LOW){      // we have just turned of
          Serial.println("Motion ended!");      // 
          pirStateB = HIGH;
           delay(10000);  // Tijd lamp aan is
          }
        }
      } 
      

      So please…
      Whe you have time…

  35. […] Um bom exemplo é o projeto de um alarme disparado por movimento que utiliza um desses sensores passivos de infravermelho, ou PIR – passive infrared – como são conhecidos no meio técnico. Eles são aqueles utilizados para acender as luzes do hall do elevador quando tem alguém por ali. Basicamente, o sensor mede a quantidade de radiação infravermelha naquele ambiente. Como todo objeto que está com a temperatura acima do zero absoluto emite radiação infravermelha, quando alguém entra no hall, o sensor percebe uma mudança na radiação naquele lugar e dispara o circuito para acender a lâmpada por um determinado período. No projeto em questão, a ideia é usar um desses sensores ligados a um Arduino para disparar um sinal sonoro quando uma mudança for detectada pelo sensor. Trata-se de um projeto bem simples, mas que é um bom começo para você se familiarizar com os conceitos de entradas e saídas da plataforma Arduino. Veja instruções detalhadas aqui. […]