Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 46

m/s 187-189 arduino cook-book 2nd Edition oreilly

6.3 Detecting Motion (Integrating Passive Infrared Detectors)


Problem
You want to detect when people are moving near a sensor.

Solution
Use a motion sensor such as a Passive Infrared (PIR) sensor to change values on a digital
pin when someone moves nearby.
Sensors such as the SparkFun PIR Motion Sensor (SEN-08630) and the Parallax PIR
Sensor (555-28027) can be easily connected to Arduino pins, as shown in Figure 6-3.

Check the data sheet for your sensor to identify the correct pins. The Parallax sensor
has pins marked “OUT,” “-,” and “+” (for Output, Gnd, and +5V). The SparkFun
sensor is marked with “Alarm,” “GND,” and “DC” (for Output, Gnd, and +5V).
The following sketch will light the LED on Arduino pin 13 when the sensor detects
motion:
/*
PIR sketch
a Passive Infrared motion sensor connected to pin 2
lights the LED on pin 13
*/
const int ledPin = 13; // choose the pin for the LED
const int inputPin = 2; // choose the input pin (for the PIR sensor)
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare pushbutton as input
}
void loop(){
int val = digitalRead(inputPin); // read input value
if (val == HIGH) // check if the input is HIGH

{
digitalWrite(ledPin, HIGH); // turn LED on if motion detected
delay(500);
digitalWrite(ledPin, LOW); // turn LED off
}
}

Discussion
This code is similar to the pushbutton examples shown in Chapter 5. That’s because
the sensor acts like a switch when motion is detected. Different kinds of PIR sensors
are available, and you should check the information for the one you have connected.
Some sensors, such as the Parallax, have a jumper that determines how the output
behaves when motion is detected. In one mode, the output remains HIGH while motion
is detected, or it can be set so that the output goes HIGH briefly and then LOW when
triggered. The example sketch in this recipe’s Solution will work in either mode.
Other sensors may go LOW on detecting motion. If your sensor’s output pin goes LOW
when motion is detected, change the line that checks the input value so that the LED
is turned on when LOW:
if (val == LOW) // motion when the input is LOW
PIR sensors come in a variety of styles and are sensitive over different distances and
angles. Careful choice and positioning can make them respond to movement in part of
a room, rather than all of it.
PIR sensors respond to heat and can be triggered by animals such as cats
and dogs, as well as by people and other heat sources.
6.3.2 Sketch for infrared motion detection
The first thing you may notice about the following PIR sensor code is how the calibration time is used to essentially stall the
loop() from reading the PIR sensor until 30 seconds have passed. This is because the PIR sensor needs time to create an
accurate map of the environment to compare against. The next thing to note is how the loop() method contains a conditional
statement to detect whether the sensor is returning HIGH or LOW and how long it’s been pulled HIGH, if it has been. The
Parallax PIR sensor returns HIGH until the motion ceases, so by keeping track of the amount of time since the sensor was
pulled HIGH, you can determine how long the object or entity moved in the field of vision of the PIR
sensor (see the following listing).
When the motion ends, the program writes the duration of the motion in front of the PIR sensor to the serial monitor.
Arduino - PIR Sensor
Advertisements

 Previous Page
Next Page  

PIR sensors allow you to sense motion. They are used to detect whether a human
has moved in or out of the sensor’s range. They are commonly found in
appliances and gadgets used at home or for businesses. They are often referred
to as PIR, "Passive Infrared", "Pyroelectric", or "IR motion" sensors.

Following are the advantages of PIR Sensors −

 Small in size

 Wide lens range

 Easy to interface

 Inexpensive

 Low-power

 Easy to use

 Do not wear out

PIRs are made of pyroelectric sensors, a round metal can with a rectangular
crystal in the center, which can detect levels of infrared radiation. Everything
emits low-level radiation, and the hotter something is, the more radiation is
emitted. The sensor in a motion detector is split in two halves. This is to detect
motion (change) and not average IR levels. The two halves are connected so that
they cancel out each other. If one-half sees more or less IR radiation than the
other, the output will swing high or low.

PIRs have adjustable settings and have a header installed in the 3-pin
ground/out/power pads.

For many basic projects or products that need to detect when a person has left or
entered the area, PIR sensors are great. Note that PIRs do not tell you the
number of people around or their closeness to the sensor. The lens is often fixed
to a certain sweep at a distance and they are sometimes set off by the pets in the
house.

Components Required
You will need the following components −

 1 × Breadboard

 1 × Arduino Uno R3
 1 × PIR Sensor (MQ3)

Procedure
Follow the circuit diagram and make the connections as shown in the image
below.

Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language
will control your circuit. Open a new sketch File by clicking New.
Arduino Code
#define pirPin 2
int calibrationTime = 30;
long unsigned int lowIn;
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int PIRValue = 0;

void setup() {
Serial.begin(9600);
pinMode(pirPin, INPUT);
}

void loop() {
PIRSensor();
}

void PIRSensor() {
if(digitalRead(pirPin) == HIGH) {
if(lockLow) {
PIRValue = 1;
lockLow = false;
Serial.println("Motion detected.");
delay(50);
}
takeLowTime = true;
}
if(digitalRead(pirPin) == LOW) {
if(takeLowTime){
lowIn = millis();takeLowTime = false;
}
if(!lockLow && millis() - lowIn > pause) {
PIRValue = 0;
lockLow = true;
Serial.println("Motion ended.");
delay(50);
}
}
}

Code to Note
PIR sensor has three terminals - Vcc, OUT and GND. Connect the sensor as follows

 Connect the +Vcc to +5v on Arduino board.

 Connect OUT to digital pin 2 on Arduino board.

 Connect GND with GND on Arduino.

You can adjust the sensor sensitivity and delay time via two variable resistors
located at the bottom of the sensor board.

Once the sensor detects any motion, Arduino will send a message via the serial
port to say that a motion is detected. The PIR sense motion will delay for certain
time to check if there is a new motion. If there is no motion detected, Arduino will
send a new message saying that the motion has ended.

Result
You will see a message on your serial port if a motion is detected and another
message when the motion stops.
How PIR Sensor Works and How To Use It with
Arduino
How It Works

First let’s explain the working principle. The module actually consists of a Pyroelectric sensor which
generates energy when exposed to heat.

That means when a human or animal body will get in the range of the sensor it will detect a movement
because the human or animal body emits heat energy in a form of infrared radiation. That’s where the
name of the sensor comes from, a Passive Infra-Red sensor. And the term “passive” means that sensor
is not using any energy for detecting purposes, it just works by detecting the energy given off by the
other objects.
The module also consists a specially designed cover named Fresnel lens, which focuses the infrared
signals onto the pyroelectric sensor.

The HC-SR501 PIR Sensor Module


The module has just three pins, a Ground and a VCC for powering the module and an output pin which
gives high logic level if an object is detected. Also it has two potentiometers. One for adjusting the
sensitivity of the sensor and the other for adjusting the time the output signal stays high when object is
detected. This time can be adjusted from 0.3 seconds up to 5 minutes.

The module has three more pins with a jumper between two of them. These pins are for selecting the
trigger modes. The first one is called “non-repeatable trigger” and works like this: when the sensor
output is high and the delay time is over, the output will automatically change from high to low level.
The other mode called “repeatable trigger” will keep the output high all the time until the detected
object is present in sensor’s range.

Components needed for this tutorial

You can get the components from any of the sites below:

 HC-SR501 PIR Sensor Module…….. Amazon / Banggood / GearBest / DealExtreme / ICStation

 5V Relay Module………………………….. Amazon / Banggood / GearBest / DealExtreme / ICStation

 Arduino Board……………………………… Amazon / Banggood / GearBest / DealExtreme / ICStation

 Breadboard and Jump Wires…………. Amazon / Banggood / GearBest / DealExtreme / ICStation

 Cable, Plug, Socket

*Please note: These are affiliate links. I may make a commission if you buy the components through
these links.
I would appreciate your support in this way!

Circuit Schematic
As an example for this tutorial I will make a circuit that will turn on a high voltage lamp when the
sensor will detect an object. Here’s the circuit schematics. The output pin of the sensor will be
connected to pin number 8 on the Arduino Board and when an object will be detected the pin number
7 will activate the relay module and the high voltage lamp will turn on. For more details how the relay
module works, you can check my Arduino Relay Tutorial. (Keep in minds that we use high voltage in the
example, so you should be very caution, because I don’t take any responsibility of your actions)

Source Code

Here’s the Arduino Code for this example. It’s quite simple. We just need to define the PIR Sensor pin
as input and the relay pin as output. Using the digitalRead() function we will read the output of the
sensor and if its high or if an object is detected it will activate the relay. For activating the relay module
we will send a logic low as the relay input pin works inversely.

1. /* Arduini PIR Motion Sensor Tutorial


2. *
3. * by Dejan Nedelkovski, www.HowToMechatronics.com
4. *
5. */
6. int pirSensor = 8;
7. int relayInput = 7;
8.
9. void setup() {
10. pinMode(pirSensor, INPUT);
11. pinMode(relayInput, OUTPUT);
12. }
13.
14. void loop() {
15. int sensorValue = digitalRead(pirSensor);
16.
17. if (sensorValue == 1) {
18. digitalWrite(relayInput, LOW); // The Relay Input works Inversly
19. }
20. }

The demonstration of the example can be seen at the end of the video attached above. Note that after
powering the sensor module it needs about 20 – 60 seconds to “warm-up” in order to function
properly. Now when you will put your hand in front of the sensor the relay will activate the lamp. But
note that even if you move your hand constantly the lamp will turn off after the adjusted delay time is
over because the PIR sensor is in “non-repeatable trigger” mode. If you change the sensor with the
jumper to the “repeatable trigger” mode and you constantly move the hand, the lamp will be
constantly on as well and it will turn off after the movement is gone and the set delay time is over.
PIRsense code

Introduction
This sketch will detect if the PIR motion sensor switches on, and when it
is off long enough to be sure that there is no motion detected anymore.

For other programs, see the PIR Motion Sensors-section in the


Playground.

Code
/*
* //////////////////////////////////////////////////
* //making sense of the Parallax PIR sensor's output
* //////////////////////////////////////////////////
*
* Switches a LED according to the state of the sensors output pin.
* Determines the beginning and end of continuous motion sequences.
*
* @author: Kristian Gohlke / krigoo (_) gmail (_) com / http://krx.at
* @date: 3. September 2006
*
* kr1 (cleft) 2006
* released under a creative commons "Attribution-NonCommercial-ShareAlike 2.0" license
* http://creativecommons.org/licenses/by-nc-sa/2.0/de/
*
*
* The Parallax PIR Sensor is an easy to use digital infrared motion sensor module.
* (http://www.parallax.com/detail.asp?product_id=555-28027)
*
* The sensor's output pin goes to HIGH if motion is present.
* However, even if motion is present it goes to LOW from time to time,
* which might give the impression no motion is present.
* This program deals with this issue by ignoring LOW-phases shorter than a given time,
* assuming continuous motion is present during these phases.
*
*/

/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 30;

//the time when the sensor outputs a low impulse


long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low


//before we assume all motion has stopped
long unsigned int pause = 5000;

boolean lockLow = true;


boolean takeLowTime;

int pirPin = 3; //the digital pin connected to the PIR sensor's output
int ledPin = 13;

/////////////////////////////
//SETUP
void setup(){
Serial.begin(9600);
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(pirPin, LOW);

//give the sensor some time to calibrate


Serial.print("calibrating sensor ");
for(int i = 0; i < calibrationTime; i++){
Serial.print(".");
delay(1000);
}
Serial.println(" done");
Serial.println("SENSOR ACTIVE");
delay(50);
}

////////////////////////////
//LOOP
void loop(){

if(digitalRead(pirPin) == HIGH){
digitalWrite(ledPin, HIGH); //the led visualizes the sensors output pin state
if(lockLow){
//makes sure we wait for a transition to LOW before any further output is made:
lockLow = false;
Serial.println("---");
Serial.print("motion detected at ");
Serial.print(millis()/1000);
Serial.println(" sec");
delay(50);
}
takeLowTime = true;
}

if(digitalRead(pirPin) == LOW){
digitalWrite(ledPin, LOW); //the led visualizes the sensors output pin state

if(takeLowTime){
lowIn = millis(); //save the time of the transition from high to LOW
takeLowTime = false; //make sure this is only done at the start of a LOW phase
}
//if the sensor is low for more than the given pause,
//we assume that no more motion is going to happen
if(!lockLow && millis() - lowIn > pause){
//makes sure this block of code is only executed again after
//a new motion sequence has been detected
lockLow = true;
Serial.print("motion ended at "); //output
Serial.print((millis() - pause)/1000);
Serial.println(" sec");
delay(50);
}
}
}
Overview

by lady ada

PIR sensors allow you to sense motion, almost always used to detect whether a human
has moved in or out of the sensors range. They are small, inexpensive, low-power, easy
to use and don't wear out. For that reason they are commonly found in appliances and
gadgets used in homes or businesses. They are often referred to as PIR, "Passive
Infrared", "Pyroelectric", or "IR motion" sensors.

PIRs are basically made of a pyroelectric sensor  (which you can see above as the round
metal can with a rectangular crystal in the center), which can detect levels of infrared
radiation. Everything emits some low level radiation, and the hotter something is, the
more radiation is emitted. The sensor in a motion detector is actually split in two halves.
The reason for that is that we are looking to detect motion (change) not average IR levels.
The two halves are wired up so that they cancel each other out. If one half sees more or
less IR radiation than the other, the output will swing high or low.
Along with the pyroelectic sensor is a bunch of supporting circuitry, resistors and
capacitors. It seems that most small hobbyist sensors use the BISS0001 ("Micro Power PIR
Motion Detector IC") , undoubtedly a very inexpensive chip. This chip takes the output of
the sensor and does some minor processing on it to emit a digital output pulse from the
analog sensor.

Our older PIRs looked like this:


Our new PIRs have more adjustable settings and have a header installed in the 3-pin
ground/out/power pads
For many basic projects or products that need to detect when a person has left or entered
the area, or has approached, PIR sensors are great. They are low power and low cost,
pretty rugged, have a wide lens range, and are easy to interface with. Note that PIRs won't
tell you how many people are around or how close they are to the sensor, the lens is
often fixed to a certain sweep and distance (although it can be hacked somewhere) and
they are also sometimes set off by housepets. Experimentation is key!

Some Basic Stats


These stats are for the PIR sensor in the Adafruit shop which is very much  like the
Parallax one . Nearly all PIRs will have slightly different specifications, although
they all pretty much work the same. If there's a datasheet, you'll want to refer to it

 Size: Rectangular
 Price: $10.00 at the Adafruit shop
 Output: Digital pulse high (3V) when triggered (motion detected) digital low when
idle (no motion detected). Pulse lengths are determined by resistors and capacitors
on the PCB and differ from sensor to sensor.
 Sensitivity range: up to 20 feet (6 meters) 110° x 70° detection range
 Power supply: 5V-12V input voltage for most modules (they have a 3.3V regulator),
but 5V is ideal in case the regulator has different specs
 BIS0001 Datasheet  (the decoder chip used)
 RE200B datasheet  (most likely the PIR sensing element used)
 NL11NH datasheet  (equivalent lens used)
 Parallax Datasheet on their version of the sensor

More links!

 A great page on PIR sensors from GLOLAB \\

How PIRs Work

by lady ada

PIR sensors are more complicated than many of the other sensors explained in
these tutorials (like photocells, FSRs and tilt switches) because there are multiple
variables that affect the sensors input and output. To begin explaining how a
basic sensor works, we'll use this rather nice diagram
The PIR sensor itself has two slots in it, each slot is made of a special material that
is sensitive to IR. The lens used here is not really doing much and so we see that
the two slots can 'see' out past some distance (basically the sensitivity of the
sensor). When the sensor is idle, both slots detect the same amount of IR, the
ambient amount radiated from the room or walls or outdoors. When a warm body
like a human or animal passes by, it first intercepts one half of the PIR sensor,
which causes a  positive differential  change between the two halves. When the
warm body leaves the sensing area, the reverse happens, whereby the sensor
generates a negative differential change. These change pulses are what is
detected.
The PIR Sensor
The IR sensor itself is housed in a hermetically sealed metal can to improve
noise/temperature/humidity immunity. There is a window made of IR-transmissive
material (typically coated silicon since that is very easy to come by) that protects the
sensing element. Behind the window are the two balanced sensors.
Left image from Murata datasheet

Image from RE200B datasheet


You can see above the diagram showing the element window, the two pieces of
sensing material

Image from RE200B datasheet


This image shows the internal schematic. There is actually a JFET inside (a type of
transistor) which is very low-noise and buffers the extremely high impedence of
the sensors into something a low-cost chip (like the BIS0001) can sense.
Lenses
PIR sensors are rather generic and for the most part vary only in price and sensitivity.
Most of the real magic happens with the optics. This is a pretty good idea for
manufacturing: the PIR sensor and circuitry is fixed and costs a few dollars. The lens
costs only a few cents and can change the breadth, range, sensing pattern, very easily.

In the diagram up top, the lens is just a piece of plastic, but that means that the
detection area is just two rectangles. Usually we'd like to have a detection area
that is much larger. To do that, we use a simple lens  such as those found in a
camera: they condenses a large area (such as a landscape) into a small one (on
film or a CCD sensor). For reasons that will be apparent soon, we would like to
make the PIR lenses small and thin and moldable from cheap plastic, even though
it may add distortion. For this reason the sensors are actually Fresnel lenses :

Image from Sensors Magazine


The Fresnel lens condenses light, providing a larger range of IR to the sensor.
Image from BHlens.com

Image from Cypress appnote 2105


OK, so now we have a much larger range. However, remember that we actually
have two sensors, and more importantly we dont want two really big sensing-area
rectangles, but rather a scattering of multiple small areas. So what we do is split
up the lens into multiple section, each section of which is a fresnel lens.
Here you can see the multiple facet-sections
This macro shot shows the different Frenel lenses in each facet!
The different faceting and sub-lenses create a range of detection areas,
interleaved with each other. Thats why the lens centers in the facets above are
'inconsistant' - every other one points to a different half of the PIR sensing
element
Images from NL11NH datasheet
Here is another image, more qualitative but not as quantitative. (Note that the
sensor in the Adafruit shop is 110° not 90°)
Image from IR-TEC

Connecting to a PIR

by lady ada
Most PIR modules have a 3-pin connection at the side or bottom. The pinout may
vary between modules so triple-check the pinout! It's often silkscreened on right
next to the connection (at least, ours is!) One pin will be ground, another will be
signal and the final one will be power. Power is usually 3-5VDC input but may be
as high as 12V. Sometimes larger modules don't have direct output and instead
just operate a relay in which case there is ground, power and the two switch
connections.
The output of some relays may be 'open collector' - that means it requires a
pullup resistor. If you're not getting a variable output be sure to try attaching a
10K pullup between the signal and power pins.
An easy way of prototyping with PIR sensors is to connect it to a breadboard since
the connection port is 0.1" spacing. Some PIRs come with header on them already,
the one's from adafruit have a straight 3-pin header on them for connecting a
cable
For our PIR's the red cable is + voltage power, black cable is - ground power and yellow
is the signal out. Just make sure you plug the cable in as shown above! If you get it
backwards you won't damage the PIR but it won't work.

Testing a PIR

by lady ada
Now when the PIR detects motion, the output pin will go "high" to 3.3V and light
up the LED!
Once you have the breadboard wired up, insert batteries and wait 30-60 seconds
for the PIR to 'stabilize'. During that time the LED may blink a little. Wait until the
LED is off and then move around in front of it, waving a hand, etc, to see the LED
light up!

Retriggering
There's a couple options you may have with your PIR. First up we'll explore the
'Retriggering' option. 
Once you have the LED blinking, look on the back of the PIR sensor and make sure that
the jumper is placed in the L position as shown below. 
Now set up the testing board again. You may notice that when connecting up the PIR
sensor as above, the LED does not stay on when moving in front of it but actually turns
on and off every second or so. That is called "non-retriggering".
Now change the jumper so that it is in the H position. If you set up the test, you will
notice that now the LED does stay on the entire time that something is moving. That is
called "retriggering".

(The graphs above are from the BISS0001 datasheet, they kinda suck)
For most applications, "retriggering" (jumper in H position as shown below) mode
is a little nicer.
If you need to connect the sensor to something edge-triggered, you'll want to set it to
"non-retriggering" (jumper in L position).

Changing sensitivity

The Adafruit PIR has a trimpot on the back for adjusting sensitivity. You can adjust this if
your PIR is too sensitive or not sensitive enough - clockwise makes it more sensitive.

Changing Pulse Time and Timeout Length


There are two 'timeouts' associated with the PIR sensor. One is the "Tx" timeout: how long
the LED is lit after it detects movement - this is easy to adjust on Adafruit PIR's because
there's a potentiometer. 

The second is the "Ti" timeout which is how long the LED is guaranteed to be off when
there is no movement. This one is not  easily changed but if you're handy with a soldering
iron it is within reason.

First, lets take a look at the BISS datasheet again

On Adafruit PIR sensors, there's a little trim potentiometer labeled  TIME. This is a 1


Megaohm adjustable resistor which is added to a 10K series resistor. And  C6 is 0.01uF
so 

Tx = 24576 x (10K + Rtime) x 0.01uF

If the Rtime potentiometer is turned all the way down counter-clockwise (to 0 ohms) then

Tx = 24576 x (10K) x 0.01uF = 2.5 seconds (approx)

If the Rtime potentiometer is turned all the way up clockwise to 1 Megaohm then

Tx = 24576 x (1010K) x 0.01uF = 250 seconds (approx)

If RTime is in the middle, that'd be about 120 seconds (two minutes) so you can tweak it
as necessary. For example if you want motion from someone to turn on a fan for a
minimum of 1 minute, set the Rtime potentiometer to about 1/4 the way around.  

For older/other PIR sensors

If you have a PIR sensor from somewhere else that does not have a potentiometer adjust,
you can trace out the adjustment resistors this way:
Determining R10 and R9 isnt too tough. Unfortunately this PIR sensor is
mislabeled (it looks like they swapped R9 R17). You can trace the pins by looking
at the BISS001 datasheet and figuring out what pins they are - R10 connects to
pin 3 and R9 connects to pin 7. the capacitors are a little tougher to determine,
but you can 'reverse engineer' them from timing the sensor and solving!
For example:
Tx is = 24576 * R10 * C6 = ~1.2 seconds 
R10 = 4.7K and C6 = 10nF
Likewise,
Ti = 24 * R9 * C7 = ~1.2 seconds 
R9 = 470K and C7 = 0.1uF
You can change the timing by swapping different resistors or capacitors. For a
nice tutorial on this, see Keith's PIR hacking page .

Using a PIR

by lady ada

Reading PIR Sensors


Connecting PIR sensors to a microcontroller is really simple. The PIR acts as a digital
output so all you need to do is listen for the pin to flip high (detected) or low (not
detected).

Its likely that you'll want reriggering, so be sure to put the jumper in
the H position!
Power the PIR with 5V and connect ground to ground. Then connect the output to
a digital pin. In this example we'll use pin 2.

The code is very simple, and is basically just keeps track of whether the input to pin 2 is
high or low. It also tracks the state of the pin, so that it prints out a message when
motion has started and stopped.

Copy Code

1. /*
2. * PIR sensor tester
3. */
4.
5. int ledPin = 13; // choose the pin for the LED
6. int inputPin = 2; // choose the input pin (for PIR sensor)
7. int pirState = LOW; // we start, assuming no motion detected
8. int val = 0; // variable for reading the pin status
9.
10. void setup() {
11. pinMode(ledPin, OUTPUT); // declare LED as output
12. pinMode(inputPin, INPUT); // declare sensor as input
13.
14. Serial.begin(9600);
15. }
16.
17. void loop(){
18. val = digitalRead(inputPin); // read input value
19. if (val == HIGH) { // check if the input is HIGH
20. digitalWrite(ledPin, HIGH); // turn LED ON
21. if (pirState == LOW) {
22. // we have just turned on
23. Serial.println("Motion detected!");
24. // We only want to print on the output change, not state
25. pirState = HIGH;
26. }
27. } else {
28. digitalWrite(ledPin, LOW); // turn LED OFF
29. if (pirState == HIGH){
30. // we have just turned of
31. Serial.println("Motion ended!");
32. // We only want to print on the output change, not state
33. pirState = LOW;
34. }
35. }
36. }

Don't forget that there are some times when you don't need a microcontroller. A PIR
sensor can be connected to a relay (perhaps with a transistor buffer) without a micro!
Introducing the PIR Motion Sensor
The PIR motion sensor is ideal to detect movement. PIR stand for “Passive
Infrared”. Basically, the PIR motion sensor measures infrared light from objects
in its field of view.

So, it can detect motion based on changes in infrared light in the environment.
It is ideal to detect if a human has moved in or out of the sensor range.

RELATED CONTENT: Like ESP8266? Check out Home Automation Using


ESP8266

The sensor in the figure above has two built-in potentiometers to adjust the
delay time (the potentiometer at the left) and the sensitivity (the potentiometer
at the right).

Pinout
Wiring the PIR motion sensor to an Arduino is pretty straightforward – the
sensor has only 3 pins.

 GND – connect to ground

 OUT – connect to an Arduino digital pin

 5V – connect to 5V
Parts required
Here’s the required parts  for this project

 1x PIR Motion Sensor (Click to see on eBay or Click to see on Amazon)


 1x Arduino (Click to see on Amazon)
 1x LED

 Jumper Cables (Click to see on Amazon)

Schematics
Assemble all the parts by following the schematics below.

DOWNLOAD FREE PDF: Arduino eBook with 18+ Projects


 

Code
Upload the following code.

/*  
    Arduino with PIR motion sensor
    For complete project details, visit: http://RandomNerdTutorials.com/pirsensor
    Modified by Rui Santos based on PIR sensor by Limor Fried
*/
 
int led = 13;         // the pin that the LED is atteched to
int sensor = 2;       // the pin that the sensor is atteched to
int state = LOW;      // by default, no motion detected
int val = 0;          // variable to store the sensor status (value)

void setup() {
  pinMode(led, OUTPUT);      // initalize LED as an output
  pinMode(sensor, INPUT);    // initialize sensor as an input
  Serial.begin(9600);        // initialize serial
}

void loop(){
  val = digitalRead(sensor);   // read sensor value
  if (val == HIGH) {           // check if the sensor is HIGH
    digitalWrite(led, HIGH);   // turn LED ON
    delay(100);                // delay 100 milliseconds
  
    if (state == LOW) {
      Serial.println("Motion detected!");
      state = HIGH;       // update variable state to HIGH
  }
 }
  else {
      digitalWrite(led, LOW); // turn LED OFF
      delay(200);             // delay 200 milliseconds
   
      if (state == HIGH){
        Serial.println("Motion stopped!");
        state = LOW;       // update variable state to LOW
  }
 }
}

Projects/Arduino_with_PIR_motion_sensor.ino

You might also like