Arduino – (Very) Basic motion tracking with 2 PIR sensors

Arduino 2PIR motion tracker

Took me a little while to get started but I’ve managed to wire 2 PIR infrared sensors with an Arduino to sense motion either on the left or on the right side. The result will trigger an LED to represent each PIR sensor then I also added in a servo to be controlled – so it turns left when triggered by the left sensor and so on.

First have a look at my previous tutorial – Arduino PIR motion detector circuit. Now we’re going to use 2 of them and this isn’t that different from just using one of them. However this is only a first attempt so I’ve not calibrated anything properly, for instance we can’t ascertain velocity or true direction of movement because these sensors aren’t that precise and have a wide range of detection. But hey, it’s a start!

Arduino PIR Motion Sensor Circuit Parts

2x 220 Ohm resistor (Red, Red, Brown, Gold)
2x 10K Ohm resistor (Brown, Black, Orange, Gold)
2x PIR sensor
1x Servo (has to need no more than 5v supply)
2x LED
Arduino Deumilanove w/ ATMEGA328
Breadboard / Prototyping board
Jumper/ Connector wires
Optional 9V DC power supply or use the USB power for the Arduino
You will also need a soldering iron and solder if you use the same PIR as myself.
Some sort of  temporary adhesive to hold the sensors in place.

Arduino Infrared Motion Detector Circuit

So you’ll see that its really just a lot of wires. The PIRs I’ve soldered on the wires and on their output pin there’s a 10K Ohm resistor for each going between them and the positive rail on the breadboard. The LED’s are the same layout as the basic blink tutorials, 220 Ohm resistor between the positive pin (the longer one) and the Arduino pin.

Arduino-2PIR-motion-tracker

PIR Motion Sensor Arduino Code

This isn’t too bad. Basically we set 2 sensors and have a few if statements to do shit based on if they turn on or off, so essentially they’re treated just like a couple of switches.
[ad#Google Ad in content]

/*
LUCKYLARRY.CO.UK - 2 3pin PIR sensors to track basic motion.

We have 1 sensor for left, 1 for right.

The left sensor is triggered, the LED for the left comes on and the servo moves until no motion is detected.
The same happens if the right sensor is triggered.

If both sensors detect motion then its likely the object may be between the 2 but given the field of detection
its not going to be precice. Enjoy!

*/

#include                                                 // Include servo library, you can get it from http://www.arduino.cc/playground/ComponentLib/Servo
Servo myservo;                                                    // Create a servo object
int pos = 0;                                                      // Variable to store the servo position in degrees
int pinPIRleft = 4;                                               // left infrared sensor, digital pin 4
int pinLEDleft = 8;	                                          // left LED, digital pin 8
int pinPIRright = 2;                                              // right sensor, digital pin 2
int pinLEDright = 10;                                             // right LED, digital pin 10

void setup() {
  pinMode(pinLEDleft, OUTPUT);                                    // set LEDs as outputs
  pinMode(pinLEDright, OUTPUT);
  pinMode(pinPIRleft, INPUT);                                     // set sensors as inputs
  pinMode(pinPIRright, INPUT);
  myservo.attach(9);                                              // set the servo to digital pin 9
}

void loop() {

  if (digitalRead(pinPIRleft) == LOW) {                           // if left detects motion
    digitalWrite(pinLEDleft, HIGH);                               // turn on LED
    if ((pos < 180) && (digitalRead(pinPIRright) == HIGH)) {      // if less than 180 degrees and the right sensor is off then move servo
      pos += 1;                                                   // increment servo degrees by +1
      myservo.write(pos);                                         // write the position to the servo
      delay(15);
    }
  } else {
    digitalWrite(pinLEDleft, LOW);                                // otherwise turn off LED and no servo movement
  }

  if (digitalRead(pinPIRright) == LOW) {
    digitalWrite(pinLEDright, HIGH);
    if ((pos >= 1) && (digitalRead(pinPIRleft) == HIGH)) {
      pos -= 1;
      myservo.write(pos);
      delay(15);
    }
  } else {
    digitalWrite(pinLEDright, LOW);
  }

  if ((digitalRead(pinPIRleft) == LOW) && (digitalRead(pinPIRright) == LOW)) {
    // do something here if both sensors detect movement.
  }
}

[ad#Google Ad in content]

And here it is in action:

Well, you could add a 3rd sensor to validate that an object is in front of both sensors, you’ll see that I’ve angled my sensors to try and work this with just 2 sensors. Perhaps limiting the field of detection for each sensor might also be a good thing to make it more precise.

40 Comments

  • Maybe you could the digital output of the PIR board to trigger an interrupt and then use an analog pin on the Arduino wired directly to the PIR sensor to look for the positive/negative or negative/positive pulses as the object moved from right to left or left to right? Because the PIR sensor is really two sensors in one and opposing each other, you should see a pulse based on what PIR half is triggered first and then the opposite pulse as the object enters and leaves the other sensor half.

  • Cheers Doug, not got that far with the PIR. I think I’ll wire up the Analog and look for the change as you suggest and see what that yields. I’m going to stick the setup on my robot so it will (eventually) follow people. Have you played with many other sensors?

  • Just had a look at sensing the PIR detection wave, unfortunately my PIR sensors combine their outputs via the IC, so I never get the PIR wave as it were, just the combined IC output of high/low.

  • Hi Larry, great website!
    For a project I’m looking to integrate the same system. But I don’t really get all the connections (I’m just a beginner) … Do you have a map of this? That would really help me out!
    Thx a million!

    • sorry its midnight here, but for now I’ll try and explain where everything goes – I guess putting wiring diagrams up will help out more…

      Anyway, depends on what PIR you have? I’m guessing you have 3 wires right? 2 will be for power – which you have to get the right way around otherwise they start making alot of smoke! Anyway these power cables will run into the Arduino supply via the breadboard.

      So the only thing to worry about is sensing change, to do this basically you plug in the 3rd pin/wire on the PIR to a digital output on your Arduino which also has a 10k resistor connecting this 3rd pin to the +5v power supply – in my picture this is the yellow cable going to digital pin 2 – its the easiest one to figure out on my picture. You’ll see the small green wires – these just hook up the power/ ground for the components.

      With PIR’s a good trick to debugging this is using some LEDs to show you when the sensor has been triggered – this is the basic LED setup, so power coming from a digital pin and 220 ohm resistor between this and the postive pin on the LED the ground/ negative going to the GND rail on the breadboard.

      The 2 small orange wires just connect one half the power rails to the other half.

      For the servo, the power again goes to the breadboard which is fed by the Arduino etc… but its 3rd pin again goes to a digital pin on the Arduino.

      Let me know if you need the diagrams and I’ll do them tomorrow evening for you :)

  • Thx for you fast reply! Yes I got the same Pir motion sensor than the one your using…
    I would be really thankful if you could send me the wiring diagram!
    I actually don’t need a diagram with led’s cause I’m building the application into a art installation & the led’s are not required for this….
    Thx a million for this info, it would really help me out! Seems to be really difficult to find people who know this things here in Belgium :( !

    Looking forward to your reply….

    • Here we go Philip, one sketch :) hope this helps – I kept it simple just for one PIR, for two just follow the same rules.

  • Ok the diagram is very clear! Thx for drawing it out!!!!
    I guess the servo stay’s in the same position digital port 9?
    Since the both leds have been deleted from the installation, what should I with them in the sketch?
    I know I’m terrible in this :( , but it’s my first time I’m working on Arduino, actually I have a basic knowledge of electronics but I notice that I have loads to learn, now that I’m working on this installation I shall have no other choice than learning it! take a look at http://www.philiphenderickx.be so you can see what I normally do… Well so far I don’t know how to thank you again for your advise & help! looking forward to your reply, I guess the final reply before I get this rolling…. unless I burn down my Arduino Deumilanove!
    Thx again!!!!

    • Would you believe that this gave me hassles as well? Thats why the LED’s are there as I just couldn’t get two sensors to work to start with! :)

      Leave the servo on digital pin 9 – my code should take care of it.

      The way I tackled all these projects is to start small and keep adding once I had one thing working. If you want me to I can expand the diagram for the servo.

      With the servo, 2 pins are for power – normally black and red, the yellow or white cable is the control and this can go directly to the Arduino pin, there’s no need for a pull up resistor like the PIR’s

    • Cool paintings by the way! I like the site. Just for your info: I’m actually a trained as a designer, not an electronics or programming! :) So keep going and persevere…

  • Thx! gives me hope :)!!! I’ve ordered the equipment should be delivered in 4 days! will keep you updated!
    But i really wanna thank you for all this information!! will send you some pictures of the work once it’s ready!
    soon more news!

    • Cool, send me pictures when you’re done – if you get stuck give me a shout.

  • hey larry, I got a bit delayed, was working on an exhibition.
    Finally got the tools, but doesn’t seem to work the servo moves left & right & shakes a lot… but doesn’t follow any of the movement…. the connection seems to work perfectly, so does the sketch, at least I think so, I copied the entire sketch & get no error (see picture)! could it be that the LED’s are noted inside the sketch but not in the circuit? can’t find out what’s wrong… any idea….?
    Thx a million!

    Philip

  • seems I can’t put pictures, but the Arduino control gives me the following message:Binary sketch size: 2784 bytes (of a 30720 byte maximum), the upload also seems to work… only problem is that the servo doesn’t do what he’s supposed to…???

    Regards,

    Philip

    • hmm… LED’s are just for error checking or seeing an effect, one for each sensor when triggered. It won’t matter if they’re in your circuit.

      I would do 2 things. Firstly try a sketch just to make sure you can control the servo and that its wired in correctly – should be 3 wires, two for power supply and one for control. Just to check that the servo library is running. The servos need to use no more than 5 volts.

      Next check the sensors – they need also have 3 wires, 2 for power, 1 for reading – but needs a pull up resistor, check that values are being read.

      I did have issues with getting my sensors working, but this sounds more like servo issues, when I have problems I try to break things down to smaller circuits to make sure I’ve gotten things correct(ish). You can mail me pictures etc.. at larry@ and I can take a look.

  • i am all new to this and i’m doing it for fun can all theses things be done in the US and can a novice do this protect easily please reply!!!

    • Hey John, welcome to working with Arduino!

      You can use any of these parts in the US it’ll all work the same so there’ll be no difference at least not at this level. In fact you’ll probably find it much easier to get parts in the US – checkout sparkfun.com they have a few bits.

      You’ll be glad to know I’m a complete novice and if I can do these projects then anyone can – I’m mainly a programmer so I’m now beginning to find my limits when dealing with schematics and electronics.

      Regarding the sketch you could easily add in another few PIR sensors and LEDs. Let me know how you get on and I’ll give you a hand if you get stuck.

      Larry.

  • one more thing can you sketch up this same thing but have one more sensor and led? thanks!!!

  • thanks a million!!! im ordering the parts soon and i will keep you posted.

  • so i have retyped almost all of the sketch and here is what i got,

    #include
    Servo myservo;
    int pos = 0;
    int pinPIRleft = 4;
    int pinLEDleft = 8;
    int pinPIRright = 2;
    int pinLEDright = 10;
    int pinPIRfront = 5;
    int pinLEDfront = 7;

    void setup() {
    pinMode(pinLEDleft, OUTPUT);
    pinMode(pinLEDright, OUTPUT);
    pinMode(pinLEDfront, OUTPUT);
    pinMode(pinPIRleft, INPUT);
    pinMode(pinPIRright, INPUT);
    pinMode(pinPIRfront, INPUT);
    myservo.attach(9);
    }

    void loop() {

    if (digitalRead(pinPIRleft) == LOW) {
    digitalWrite(pinLEDleft, HIGH);
    if ((pos = 1) && (digitalRead(pinPIRleft) == HIGH)) {
    pos -= 1;
    myservo.write(pos);
    delay(15);
    }
    } else {
    digitalWrite(pinLEDright, LOW);
    }

    if ((digitalRead(pinPIRleft) == LOW) && (digitalRead(pinPIRright) == LOW)) {

    }
    }

    I’m stuck on the servo moving part, I want to make it so when the front PIR is on the sensor stops in its place until PIR left or right is the only one on please help me wright the last bit

    • OK, so you want to move the 3 sensors depending on if movement is detected so it follows motion, panning a camera etc..

      If I’ve got that correct (apologies if I’m wrong) then first of all you’ll need to first check that the servo moves left and right depending on the sensor ensuring that motion is only detected on one side.

      It depends on how your circuit is configured of course so you may want to change this around slightly, also a typical servo has 180 degrees of movement, so I always calculate that range so I know exactly where its meant to be.

      The code below should do left or right and stop if the front is triggered:

      if (digitalRead(pinPIRfront) == LOW)) {
      // providing the front PIR is not detecting then we can look at left and right.
      if (digitalRead(pinPIRleft) == LOW) {
      // double check nothing is detected on the left
      if ((pos = 1) && (digitalRead(pinPIRleft) == HIGH)) {
      pos -= 1;
      myservo.write(pos);
      delay(15);
      }
      }
      } // else if the front is detecting we can do other stuff now.

      So if thats working correctly, you should see your servo turn left on the left sensor etc… I do a check first to see if the right sensor is not detecting motion – but this was originally because I had 2 sensors (I still do!) also it safegaurds against a double positive result – if both trigger then what?

      Hope that helps you out – otherwise I’ll get another PIR and buid the circuit up myself :)

  • I’m trying to get a system like this ,

    left. //turning left
    Left,front. //between left and front
    Front. // 90 deg. Only when front is only PIR on
    Right,front. //between right and front
    right. //turning right
    ,so there is “four positions” will the sketch I have work?
    Thanks so much for your help I’m very thankful :)

    • Ah no my sketch will only do 3 positions left, front or right – try this code below (adding in the servos etc..) and in the meantime I’ll get another PIR.

      /*

      This code below will check and do something if any sensor is triggered.
      If more than one sensor is triggered then the code will still execute and
      potentially cause conflicts e.g. the servo wants to turn both left and right!

      */

      if (digitalRead(pinPIRright) == HIGH) {
      // do stuff when right
      }

      if (digitalRead(pinPIRleft) == HIGH) {
      // do stuff when left
      }

      if (digitalRead(pinPIRfront) == HIGH) && (digitalRead(pinPIRright) == HIGH)) {
      // do stuff when front and right
      }

      if (digitalRead(pinPIRfront) == HIGH) && (digitalRead(pinPIRleft) == HIGH)) {
      // do stuff when front and left
      }

      if (digitalRead(pinPIRfront) == HIGH) {
      // do stuff when front
      }

      /*

      Better way is to use an ‘else’ clause so that the events are specifically controlled.
      This way we can have a designated single result/state so there will be no conflict.
      This way should also ignore any other combinations we don’t want e.g left and right

      */

      if (digitalRead(pinPIRright) == HIGH) {
      // do stuff when right
      } else {

      if (digitalRead(pinPIRleft) == HIGH) {
      // do stuff when left
      } else {

      if (digitalRead(pinPIRfront) == HIGH) && (digitalRead(pinPIRright) == HIGH)) {
      // do stuff when front and right
      } else {

      if (digitalRead(pinPIRfront) == HIGH) && (digitalRead(pinPIRleft) == HIGH)) {
      // do stuff when front and left
      } else{

      if (digitalRead(pinPIRfront) == HIGH) {
      // do stuff when front
      }
      }
      }
      }
      }

  • hey, i got my PIR sensors but only 2 came so i will go to the store later but i used your sketch and when i turned my arduino on it loads for a second and both LEDs turn on and the servo tries to move help me!!!

    • Have you got a 3rd PIR yet? – I’ll get me one and I’ll create a new post and how-to for you to follow. :)

    • Hey John I got a 3rd sensor so I’m just wiring this up now and I’ll write it up – hopefully it should help you out.

  • […] While I was doing research on sensors and arduinos I came across many related projects done by other people. I’m posting the links and videos here…These are really helping me in writting my code and setting up the arduino system. Light & Sound sensor Motion Tracking […]

  • Larry,

    by chance have you done a wire diagram, I am trying to troubleshoot the circuit and some of the connections in the pictures you have posted get lost. was seeing if you used something along the lines of fritzing.

    i get one of the sensors to work(right) but the left sensor just does not seem to budge.

  • hello,
    i don’t understand why i need a 10K Ohm resistor.

    i’m using a CEBEK c-7288 PIR sensor.
    http://img.icnea.net/E6001/docs/c-7288-ing.pdf

    With the resitor Arduino return a 11 without moving and a 1023 with moving .
    Without the resitor Arduino return a 0 without moving and a 1023 with moving .

    • the resistor is there to act as a ‘pull up resistor’ so it filters the signal from the PIR to the Arduino and gives a steady signal and filters out events being captured such as the PIR turning on or off rather than detecting movement etc…

  • […] PIR tracking […]

  • Huh, I’ve been working on a similar setup for a minimalistic auto-sentry, except I have three PIR sensors. Though I’ve managed to track motion with them, they seem to say they detect motion for a second after the motion has ended. This creates a weird lag and the sentry reacts like a target is still present. Is there a way I could fix this? It could be a software problem, since I’m relatively new to both programming and the Arduino…

  • Also, upon reading the last two comments above mine, I’m wondering whether the resistor might have something to do with my issue. I have no resistors anywhere in the circuit, other than anything in the Arduino. This is in fact my first Arduino project as well as first project involving electrical engineering in general. How I’ve gotten this far is still beyond me.

  • Larry,
    Is it possible to run six servo’s off this unit? We have a school project that we are trying to animate six sets of eyes in masks to track the audience. I may have to try the 3 pir sensors also.

    • yep, but you’ll need to run the power from the servos from a different power supply to the Arduino, 2 servos seems to be the limit for it’s 5 volt supply after that things get patchy.

  • could anyone please send more detailed picture or drawing on wirings? I tried to follow scheme above but not working and I think it must be my beginner wirings or logic into electronics. but, I would relay like to be able to do this.
    I could be with no LEDs
    Thanks

  • Hi great code, need some help.
    I need to keep the leds on for set period of time, then turn of.
    i need the servo to go to 180 degrees stop for set time, then return to 0 degrees. My first time with programing, can’t seem find something thats suit, my purpose

    Thanks Steve

  • Hi Im on the opposite side of this project as I believe my neighbors who we have been feuding for years as placed a PIR on my home which is now constantly making my house vibrate, thus irritating and annoying us. We need to first know how can we detect the location and more importantly how to deactivate and destroy this device so we can get some sleep and peace. Thanks.

  • Good day Larry,
    I am trying to make a motion tracking turret. For example, if an object walks in range of a sensor I want the turret to point and follow the object anywhere it goes. For simplicity I just want to follow the object along the x axis. Researching this i am seeing a lot of people achieving this using a webcam, however, I am trying to avoid that method even though it might be more accurate. I was looking at your tutorial on (Very) Basic motion tracking with 2 PIR sensors, and wondering if this approach would be suitable for my application.

    Any feedback would be greatly appreciated

    Regards,
    Nicholas Wyatt

  • any body can gide me that tracking an ir body using pir sensor is a reasonable decsion? what range can it provide? what if i use an array of phototransistors? i want a range of one meter atleast..plz guide…

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>