Infrared motion sensor arduino wiring diagram. PIR sensor: description and connection instructions. The principle of operation of pyroelectric motion sensors

The topic of today's lesson is a motion sensor based on the pyroelectric effect (PIR, passive infrared motion sensor). Such sensors are often used in security systems and in everyday life to detect movement in a room. For example, the principle of motion detection is based on the automatic switching on of the light in the entrance or in the bathroom. Pyroelectric sensors are quite simple, inexpensive and unpretentious in installation and maintenance. By the way, there are other ways to detect motion. Today, computer vision systems are increasingly used to recognize objects and the trajectory of their movement. In the same security systems, laser detectors are used, which give an alarm signal when the beam is crossed. Thermal imaging sensors are also used, capable of detecting the movement of only living beings.

1. The principle of operation of pyroelectric motion sensors

Pyroelectrics are dielectrics that create an electric field when their temperature changes. Based on pyroelectrics, temperature sensors are made, for example, LHI778 or IRA-E700. Each such sensor contains two sensitive elements 1×2 mm in size, connected with opposite polarity. And as we will see later, the presence of exactly two elements will help us detect motion. This is what Murata's IRA-E700 sensor looks like. In this lesson, we will work with the HC-SR501 motion sensor, which has one such pyroelectric sensor. From above, the pyroelectric is surrounded by a hemisphere, divided into several segments. Each segment of this sphere is a lens that focuses thermal radiation on different areas of the PIR sensor. Often a Fresnel lens is used as a lens.
The principle of operation of the motion sensor is as follows. Let's assume that the sensor is installed in an empty room. Each sensitive element receives a constant dose of radiation, which means that the voltage on them has a constant value (left figure).
As soon as a person enters the room, he first enters the field of view of the first element, which leads to the appearance of a positive electrical impulse on it (central figure). The person is moving, and his thermal radiation through the lenses hits the second PIR element, which generates a negative pulse. Electronic circuit The motion sensor registers these multidirectional pulses and draws conclusions that a person has fallen into the field of view of the sensor. A positive pulse is generated at the output of the sensor (right figure).

2. Setting up the HC-SR501

In this lesson, we will use the HC-SR501 module. This module is very common and is used in many DIY projects due to its low cost. The sensor has two variable resistors and a jumper for setting the mode. One of the potentiometers controls the sensitivity of the device. The larger it is, the further the sensor “sees”. Sensitivity also affects the size of the detected object. For example, you can exclude a dog or a cat from triggering.
The second potentiometer adjusts the response time T . If the sensor detects movement, it generates a positive pulse of length T . Finally, the third control is a jumper that switches the sensor mode. Pregnant L the sensor is counting T from the very first operation. Let's say we want to control the light in the bathroom. Entering the room, a person will trigger the sensor, and the light will turn on exactly for a while T . At the end of the period, the output signal will return to its original state, and the sensor will give the next trigger. Pregnant H sensor starts timing T every time after motion is detected. In other words, any human movement will reset the countdown timer. T . By default, the jumper is in the state H .

3. Connecting HC-SR501 to Arduino Uno

For connection to a microcontroller or directly to a relay, the HC-SR501 has three pins. We connect them to the Arduino as follows:
HC-SR501 GND VCC OUT
Arduino Uno GND +5V 2
circuit diagram
Layout appearance
Program As already mentioned, the digital output of the HC-SR501 sensor generates high level signal when triggered. Let's write a simple program, which will send to the serial port "1" if the sensor saw movement, and "0" otherwise. const int movPin = 2 void setup() ( Serial.begin(9600); pinMode(movPin, INPUT); ) void loop()( int val = digitalRead(movPin); Serial.println(val); delay(100); ) We load the program on Arduino and check the operation of the sensor. You can tweak the sensor settings and see how it affects its operation.

4. Light control based on motion sensor

The next step is the automatic lighting system. In order to control the lighting in the room, we need to add a relay to the circuit. We will use a relay module with protection based on optocoupler, which we already wrote about in one of the lessons (a lesson about relays). Attention! This circuit lights the lamp from a 220 volt network. It is recommended to check all connections seven times before connecting the circuit to the household power supply. circuit diagram
Layout appearance
Program Now let's write a program that, when the sensor is triggered, will turn on the relay, and therefore the lighting in the room. const int movPin = 2; const int relPin = 3; void setup() ( Serial.begin(9600); pinMode(movPin, INPUT); pinMode(relPin, OUTPUT); ) void loop()( int val = digitalRead(movPin); if (val) digitalWrite(relPin, HIGH) ; else digitalWrite(relPin, LOW); ) We load the program on Arduino, carefully connect the circuit to the household network and check the operation of the sensor. Conclusion Motion sensors are all around us. Thanks to security systems, they can be found in almost every room. As we found out, they are very easy to use and can be easily integrated into any Arduino or Raspberry Pi project. Here are a few situations and places where a motion sensor can come in handy:
  • automatic switching on of the light in the entrance of the house, in the bathroom and toilet, in front of front door into the room;
  • alarm indoors and outdoors;
  • automatic door opening;
  • automatic activation of the security camera.
As mentioned at the very beginning, there are other ways to detect motion. We'll talk about them in the next lesson!

PIR (passive infrared sensors) sensors react to movement, through which they are often used in alarm systems. These sensors are small, cheap, energy-saving, easy to operate, and virtually indestructible. In addition to PIR, such sensors are called pyroelectric and infrared motion sensors.

Pirloelectric motion sensor - general information

PIR motion sensors essentially consist of a pyroelectric sensing element (cylindrical part with a rectangular crystal in the center) that detects the level of infrared radiation. Everything around emits a small level of radiation. How more temperature, the higher the radiation level. The sensor is actually divided into two parts. This is due to the fact that it is not the level of radiation that is important to us, but directly the presence of movement within its sensitivity zone. The two parts of the sensor are set up so that if one half picks up more radiation than the other, the output signal will generate a high or low value.

PIR sensors are great for projects that need to detect the presence or absence of a person within a specific workspace. In addition to the advantages of such sensors listed above, they have a large sensitivity zone. However, please note that pyroelectric sensors will not give you information about how many people are around and how close they are to the sensor. In addition, they can work on pets.

General technical information

These specifications refer to PIR sensors sold in the Adafruit store. The principle of operation of similar sensors is similar, although the technical specifications may differ. So before working with a PIR sensor, check out its datasheet.

  • Shape: Rectangle;
  • Price: around $10.00 at the Adafruit store;
  • Output signal: digital pulse high (3V) when there is motion and digital signal low when there is no movement. The pulse length depends on the resistors and capacitors on the module itself and is different in different sensors;
  • Sensitivity range: up to 6 meters. Viewing angle 110° x 70°;
  • Power supply: 3V - 9V, but the best option- 5 volts;

The principle of operation of pyroelectric (PIR) motion sensors

PIR sensors are not as simple as it might seem at first glance. The main reason - a large number of variables that affect its input and output signals. To explain the basics of how PIR sensors work, we use the figure below.

The pyroelectric motion sensor consists of two main parts. Each part includes a special material that is sensitive to infrared radiation. In this case, the lenses do not particularly affect the operation of the sensor, so we see two areas of sensitivity of the entire module. When the sensor is at rest, both sensors detect the same amount of radiation. For example, this could be room radiation or environment on the street. When a warm-blooded object (human or animal) passes by, it crosses the sensitivity zone of the first sensor, as a result of which two different meanings radiation. When a person leaves the sensitivity zone of the first sensor, the values ​​are aligned. It is the changes in the readings of the two sensors that are recorded and generate HIGH or LOW pulses at the output.

PIR sensor design

The sensitive elements of the PIR sensor are installed in a metal hermetic case, which protects against external noise, temperature changes and humidity. The rectangle in the center is made of a material that lets through infrared radiation(usually a silicone-based material). Behind this plate are two sensitive elements.

Figure from Murata datasheet:

lenses

Infrared motion sensors are almost identical in their structure. The main differences are sensitivity, which depends on the quality of the sensitive elements. In this case, optics play a significant role.

The figure above shows an example of a plastic lens. This means that the sensitivity range of the sensor consists of two rectangles. But, as a rule, we need to provide large viewing angles. To do this, you can use lenses similar to those used in cameras. In this case, the lens for the motion sensor should be small, thin and made of plastic, although it adds noise to the measurements. Therefore, most PIR sensors use Fresnel lenses (figure from Sensors Magazine):

Fresnel lenses concentrate radiation, significantly expanding the sensitivity range of pyro sensors (Figure from BHlens.com)

Figure from Cypress appnote 2105:

Now we have a much larger sensitivity range. At the same time, we remember that we have two sensitive elements and we need not so much two large rectangles as a large number of small sensitivity zones. To do this, the lens is divided into several sections, each of which is a separate Fresnel lens.

PIR motion sensor connection


Most infrared motion sensor modules have three connectors on the back. The pinout may vary, so check it before connecting! Usually, corresponding inscriptions are made next to the connectors. One connector goes to the ground, the second gives the signal we are interested in from the sensors, the third - the ground. The supply voltage is typically 3-5 volts DC. However, sometimes there are sensors with a supply voltage of 12 volts. Some large sensors do not have a separate signal pin. Instead, a relay with ground, power, and two switches is used.

To prototype your device using infrared motion sensor, it is convenient to use circuit board, since most of these modules have three connectors, the distance between which is calculated exactly for the breadboard holes.

In our case, the red cable corresponds to power, black to ground, and yellow to signal. If you connect the cables incorrectly, the sensor will not fail, but it will not work.

PIR Motion Sensor Testing

Assemble the circuit according to the picture above. As a result, when the PIR sensor detects movement, a HIGH signal will be generated at the output, which corresponds to 3.3 V, and the LED will light up.

Please note that the pyroelectric sensor must "stabilise". Install batteries and wait 30-60 seconds. During this time, the LED may flash. Wait until the blinking stops and you can start waving your arms and walking around the sensor, watching the LED light up!

Setting the sensitivity

Many infrared motion sensors, including those from Adafruit, have a small potentiometer to adjust the sensitivity. Turning the potentiometer clockwise adds sensitivity to the sensor.

Changing pulse time and time between pulses

When we consider PIR sensors, two "delay" times are important. First time -Tx: how long the LED stays on after motion is detected. On many pyroelectric modules, this time is controlled by a built-in potentiometer. The second time interval is Ti: how long the LED is guaranteed not to light up when there was no movement. Changing this parameter is not so easy, you may need a soldering iron for this.

Let's take a look at the BISS datasheet:

Sensors from Adafruit have a potentiometer marked TIME. This is a 1 mega ohm variable resistor added to the 10 k ohm resistors. Capacitor C6 has a capacitance of 0.01uF, so:

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

When the Rtime potentiometer is in the "zero" - fully counter-clockwise - position (0 MΩ):

Tx = 24576 x (10 kΩ) x 0.01 uF = 2.5 seconds (approx.) When the Rtime potentiometer is turned fully clockwise (1 MΩ):

Tx = 24576 x (1010 kΩ) x 0.01 uF = 250 seconds (approx.)

In the middle position of RTime, the time will be about 120 seconds (two minutes). That is, if you want to track the movement of an object at a rate of once per minute, turn the potentiometer 1/4 turn.

Connecting PIR Motion Sensor to Arduino


Let's write a program for reading values ​​from a pyroelectric motion sensor. Connecting the PIR sensor to the microcontroller is simple. The sensor outputs a digital signal, so all you need to do is read the HIGH (motion detected) or LOW (no motion) signal from the Arduino pin.

When doing this, do not forget to set the connector to position H!

Apply 5 volts to the sensor. The earth is connected to the earth. After that, connect the signal pin from the sensor to the digital pin on the Arduino. IN this example pin 2 is used.


The program is simple. In fact, it monitors the state of pin 2. Namely: what signal is on it: LOW or HIGH. In addition, a message is displayed when the state of the pin changes: there is movement or there is no movement.

* check PIR motion sensor

int ledPin = 13; // initialize the pin for the LED

int inputPin = 2; // initialize the pin to receive a signal from the pyroelectric motion sensor

int pirState = LOW; // start the program, assuming there is no movement

intval = 0; // variable for reading pin state

pinMode(ledPin, OUTPUT); // declare LED as OUTPUT

pinMode(inputPin, INPUT); // declare the sensor as an INPUT

Serial.begin(9600);

val = digitalRead(inputPin); // read the value from the sensor

if (val == HIGH) ( // check if the read value is HIGH

digitalWrite(ledPin, HIGH); // turn on the LED

if (pirState == LOW) (

// we just included

Serial.println("Motion detected!");

pirState=HIGH;

digitalWrite(ledPin, LOW); // turn off the LED

if (pirState == HIGH)(

// we just turned it off

Serial.println("Motion ended!");

// we're displaying the change, not the state, on the serial monitor

Do not forget that a microcontroller is not always needed to work with a pyroelectric sensor.

Today we will analyze the project of connecting a PIR sensor (motion) to Arduino and organize automatic sending of e-mail when the sensor is triggered. Arduino is the heart of this project - it reads the IR sensor, and when motion is detected, it gives it to the computer via USB port command to send a letter. Processing of the signal coming to the computer is implemented using the Python program.

Model Assembly Parts List

To build the project described in this tutorial, you will need the following parts:

  • Arduino UNO or equivalent (more on how to choose an Arduino);
  • PIR sensor ($2 will do)
  • brainboard (can be bought for $2.4);
  • male-male wires (you can buy such a bundle with a large margin).

You will also need a computer with an Internet connection, through which we will send e-mail! The role of the computer in this lesson can be played.

Scheme of connecting a PIR sensor to Arduino

Only the PIR sensor needs to be connected to the Arduino in this project, so the wires from the sensor can be connected directly to the Arduino. But since in this case, it is more convenient to hold the wires a little looser using the c brainboard scheme:

Arduino sketch

The Arduino will send a message over the USB Serial connection when motion is detected. But if you send an e-mail every time the sensor is triggered, you can get a huge amount of letters. Therefore, if too little time has passed since the last signal, we will send another message.
int pirPin = 7;
int minSecsBetweenEmails = 60; // 1 min
long lastSend = -minSecsBetweenEmails * 1000;
void setup()
{
pinMode(pirPin, INPUT);
Serial.begin(9600);
}
void loop()
{
long now = millis();
if (digitalRead(pirPin) == HIGH)
{
if (now > (lastSend + minSecsBetweenEmails * 1000))
{
Serial.println("MOVEMENT"); lastSend = now;
}
else
{
Serial.println("Too soon"); )
}
delay(500);
}

The "minSecsBetweenEmails" variable can be changed to another reasonable value. In the example it is set to 60 seconds and emails will not be sent for more than one minute. To keep track of when last time the command to send e-mail was given, the variable "lastSend" is used. We initialize it with a negative number, equal to the number milliseconds specified in the "minSecsBetweenEmails" variable. This ensures that we handle the PIR sensor triggering as soon as the Arduino sketch is launched. The loop uses the Millis() function to get the number of milliseconds from the Arduino and compare it to the time since the last sensor triggered and the corresponding "MOVEMENT" message sent. If the comparison shows that too little time has passed since the last sensor operation, then despite the fact that the movement was detected, we send the message "Too soon" (Too early). Before writing a Python program to process the signal coming from the Arduino to a computer or Raspberry Pi via USB, you can check the operation of the program on the Arduino by simply opening the Serial Monitor on Arduino IDE.

Installing Python and PySerial

If the project uses a Linux computer, such as a Raspberry Pi, Python is already installed. If you are using a computer with an operating Windows system, then Python needs to be installed. In any case, you will need to install the PySerial library in order to communicate with the Arduino.

Installing Python on Windows

To install Python on Windows, download the installer from https://www.python.org/downloads/ . There have been reports of problems with PySerial on Windows when using Python 3, so we are using Python 2. Once Python is installed, a group will appear in the Start menu. But to install PySerial, you will need to use Python from command line, so let's add the appropriate directory to the Windows PATH variable.
To do this, you need to go to the Windows Control Panel, find System Properties (System Properties). Then click on the button labeled Environment Variabes and in the window that appears select Path at the bottom of System variables. Press the Edit button, and then at the end of the "Variable value", without deleting the existing text, add "; C:\Python27". Do not forget ";" after each specified folder. To check that the PATH variable has been changed correctly, at the command line, enter the command "python". A similar picture should appear:


Installing PySerial

Regardless of the used operating system, download the .tar.gz installation package for PySerial 2.6 from https://pypi.python.org/pypi/pyserial Get a file called pyserial-2.6.tar.gz When using Windows you need to unzip the file into a folder. Unfortunately, this is not a regular ZIP file, so you may need to download eg 7-zip (http://www.7-zip.org/). When using a Linux computer, such as when using a Raspberry Pi in this project, you need to open a terminal session, execute the "CD" command specifying the folder where pyserial-2.6.tar.gz was downloaded, and then run the following command to unpack the installer :
$ tar -xzf pyserial-2.6.tar.gz
Next, regardless of the operating system used, on the command line, execute the “CD” command specifying the pyserial-2.6 folder and execute the command:
sudo python setup.py install

Python code

Now let's create a Python program. To do this, copy given code to a file named "movement.py". On Linux a "nano" editor can be used, on Windows probably the easiest way to make a file is with the Python 'IDLE' editor (accessible from the Python program group on the start menu).

import time
import serial
import smtplib
TO=" [email protected]"
GMAIL_USER=" [email protected]"
GMAIL_PASS = "putyourpasswordhere"
SUBJECT = "Intrusion!!"
TEXT = "Your PIR sensor movement detected"
ser = serial.Serial("COM4", 9600)
def send_email():
print("Sending Email")
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo() smtpserver.starttls()
smtpserver.ehlo smtpserver.login(GMAIL_USER, GMAIL_PASS)
header = "To:" + TO + "\n" + "From: " + GMAIL_USER
header = header + "\n" + "Subject:" + SUBJECT + "\n"
print header
msg = header + "\n" + TEXT + "\n\n"
smtpserver.sendmail(GMAIL_USER, TO, msg)
smtpserver.close()
while True:
message = ser.readline()
print(message)
if message == "M" :
send_email()
time.sleep(0.5)

Before running the Python program, we make some changes (all of them at the top of the program). The program assumes that emails are generated from a Gmail account. If it doesn't exist, register it (even if it's only for this project). Change the value of the "TO" variable to the email address where notifications will be sent. We change the value of "GMAIL_USER" to the Gmail email address and, accordingly, the password in the next line (GMAIL_PASS). You can also change the subject and text of the message to be sent ("SUBJECT" and "TEXT"). You need to set the serial port that the Arduino is connected to in the line ser = serial.Serial("COM4", 9600) For Windows, it will be something like "COM4" for Linux - something like "/dev/tty.usbmodem621" . To which port of the computer the board is connected, we look in the Arduino IDE in the lower right corner.
After these changes, run the program from the command line / terminal: python movement.py Done! When the PIR sensor is triggered, a message will be sent to the specified e-mail shortly.

What else can you do with a PIR sensor

Now, having mastered the means of sending email with Arduino, you can start expanding the capabilities of the project. You can add other sensors, and, for example, send yourself e-mail hourly temperature reports. Of course, the PIR sensor can be used directly with the Arduino without connecting to a computer. In this case, when the sensor is triggered, you can turn on a warning sound signal, flash the LED, or turn on the lighting in the room (via a high-voltage relay).

In this tutorial, we will show you how to make a motion sensor using an ultrasonic sensor (HC-SR04) that will turn on the LED every time. Components for this lesson can be ordered at any convenient store, and eventually on our website.

The lesson is suitable for beginners, but it will also be interesting for more experienced engineers.

Step 1: Required Parts

Below is the entire list of components that will be useful to us for our lesson.

1 x Arduino board(we used Arduino Uno)
1 x LED (LED, color doesn't matter)
1 x Resistor/resistance 220 ohm
1 x development board
1 x Arduino USB cable
1 x 9V battery with clip (optional)
6 x Leads

Step 2: Positioning the Parts

First, connect the ultrasonic sensor and LED on the breadboard. Connect the short LED cable (cathode) to the GND (ground) pin of the sensor. Then install the resistor in the same row as the longer LED wire (anode) so they are connected.

Step 3: Connecting the Parts

Now you need to connect some wires on the back of the sensor. There are four pins - VCC, TRIG, ECHO and GND. After inserting the wires, you need to make the following connections:

The resistor end to the digital pin of your choice, just remember to change it later in the code.

Sensor -> Arduino
VCC -> 5V (power)
TRIG -> 5*
ECHO -> 4*
GND -> GND (ground)

* - can be connected to any two digital pins Arduino, just make sure you change them in the code later.

Step 4: Downloading the Code

Now you can connect your Arduino to your computer with a USB cable. open software Arduino and download the code you can find below. The constants are commented, so you know exactly what they do and may change them.

Const int ledPin = 6; // LED digital output const int trigPin = 5; // Digital output for connecting TRIG const int echoPin = 4; // Digital output for connecting ECHO const int ledOnTime = 1000; // Time the LED stays on after motion is detected (in milliseconds, 1000ms = 1s) const int trigDistance = 20; // Distance (and smaller value) at which the sensor is triggered (in centimeters) int duration; int distance; void setup() ( pinMode(ledPin, OUTPUT); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); ) void loop() ( digitalWrite(trigPin, LOW); digitalWrite(trigPin, HIGH); delay(1) ; digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = duration * 0.034 / 2; if (distance<= trigDistance) { digitalWrite(ledPin, HIGH); delay(ledOnTime); digitalWrite(ledPin, LOW); } delay(100); }

Step 5: End result (video)

The final result of the motion sensor and its operation can be seen in the video below.

All good projects!

PrincipleworkPIR (Passive Infra Red)-sensors

Any object with a certain temperature becomes a source of electromagnetic (thermal) radiation, including the human body. The wavelength of this radiation depends on temperature and is in the infrared part of the spectrum. This radiation is invisible to the eye and is captured only by sensors. They are also called PIR sensors.

This is an abbreviation for the words "passive infrared" or "passive infrared" sensors. Passive - because the sensors themselves do not emit, but only perceive radiation with a wavelength of 7 to 14 µm.

The person radiates warmth. Its infrared thermal image shows the temperature distribution over the surface of the body. Hotter objects look lighter, colder objects look darker, because. radiate less heat.

The PIR sensor contains a sensitive element that reacts to changes in thermal radiation. If it remains constant, no electrical signal is generated.

In order for the sensor to respond to movement, special lenses (Fresnel lenses) are used with several focusing areas, which break the overall thermal picture into active and passive zones arranged in a checkerboard pattern. A person, being in the field of operation of the sensor, occupies several active zones in whole or in part.

Therefore, even with minimal movement, there is a movement from one active zone to another, which triggers the sensor. The background thermal picture, as a rule, changes very slowly and evenly. The sensor does not respond to it. The high density of active and passive zones allows the sensor to reliably detect the presence of a person even with the slightest movement.



What else to read