[PYTHON] Make a monitoring device with an infrared sensor

Introduction

Please prepare the following items [Infrared sensor](https://www.amazon.co.jp/SODIAL-R-267-%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3% 83% AB% E7% 84% A6% E9% 9B% BB% E5% 9E% 8B% E8% B5% A4% E5% A4% 96% E7% B7% 9A% E6% A4% 9C% E5% 87% BA% E5% 99% A8PIR% E3% 83% A2% E3% 83% BC% E3% 82% B7% E3% 83% A7% E3% 83% B3 / dp / B00L11K4RQ? Ie = UTF8 & ref_ = pe_1095802_173146692) Raspberry Pi and related products [Code](https://www.amazon.co.jp/%E3%82%B9%E3%82%A4%E3%83%83%E3%83%81%E3%82%B5%E3%82 % A4% E3% 82% A8% E3% 83% B3% E3% 82% B9-SFE-PRT-08430-% E3% 82% B8% E3% 83% A3% E3% 83% B3% E3% 83% 91% E3% 83% AF% E3% 82% A4% E3% 83% A4-% E3% 83% A1% E3% 82% B9% EF% BD% 9E% E3% 83% A1% E3% 82% B9 -10% E6% 9C% AC% E3% 82% BB% E3% 83% 83% E3% 83% 88 / dp / B0079AXJ0W? Ie = UTF8 & ref_ = pe_1095802_173146692) If possible, look for the cheapest one yourself.

Connect

abc.png

sensor raspbery pi
VCC 5V
OUT GPIO25:22
GND GND:25

command

pi@raspberrypi:~$ sudo su
root@raspberrypi:/home/pi# 

Since GPIO uses 25 pins, export GPIO25 to user space. If you do not do this, you will not be able to access GPIO.

root@raspberrypi:/home/pi# echo 25 > /sys/class/gpio/export

Writing to an export file in the / sys / class / gpio directory with the echo command creates a new directory called / sys / class / gpio / gpio25 with the virtual files needed to control GPIO. Since the input from the sensor is judged this time, set in in the direction file.

root@raspberrypi:/home/pi# cd /sys/class/gpio/gpio25
root@raspberrypi:/sys/class/gpio/gpio25# echo in > direction

Now, if the sensor responds, 1 will be written to the value file, and if there is no response, 0 will be written. When the sensor is made to react and the following command is executed, 1 is written in value and the operation can be confirmed.

root@raspberrypi:/sys/class/gpio/gpio25# cat value
1

Script creation

What to make this time ・ Send an email when the infrared sensor responds

sudo nano sensor_push.py

sensor_push.py


#!/usr/bin/env python
#-*- coding: utf-8 -*-

import time
import RPi.GPIO as GPIO
import os.path
import datetime
import smtplib
from email import Encoders
from email.Utils import formatdate
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

INTAVAL = 3
SLEEPTIME = 5
SENSOR_PIN = 25

#Gmail account
ADDRESS = "Gmail address"
PASSWARD = "Gmail password"

GPIO.cleanup()
GPIO.setmode(GPIO.BCM)
GPIO.setup(SENSOR_PIN, GPIO.IN)

st = time.time()-INTAVAL

while True:
  print GPIO.input(SENSOR_PIN)
  if(GPIO.input(SENSOR_PIN) == GPIO.HIGH) and (st + INTAVAL < time.time()):
    st = time.time()
    print("Detected a person")
 
    def create_message(from_addr, to_addr, subject, body, mime=None, attach_file=None):
        
        msg = MIMEMultipart()
        msg["From"] = from_addr
        msg["To"] = to_addr
        msg["Date"] = formatdate()
        msg["Subject"] = subject
        body = MIMEText(body)
        msg.attach(body)
 
        #Attachment
        if mime != None and attach_file != None:
            attachment = MIMEBase(mime['type'],mime['subtype'])
            file = open(attach_file['path'])
            attachment.set_payload(file.read())
            file.close()
            Encoders.encode_base64(attachment)
            msg.attach(attachment)
            attachment.add_header("Content-Disposition","attachment", filename=attach_file['name'])
 
        return msg
 
    def send(from_addr, to_addrs, msg):
  
        smtpobj = smtplib.SMTP(SMTP, PORT)
        smtpobj.ehlo()
        smtpobj.starttls()
        smtpobj.ehlo()
        smtpobj.login(ADDRESS, PASSWARD)
        smtpobj.sendmail(from_addr, to_addrs, msg.as_string())
        smtpobj.close()
 
 
   if __name__ == '__main__':
 
       #destination address
       to_addr = "destination address"
 
       #Subject and body
       subject = "Thieves!Fire!Murder!"
       body = "Text"
 
       #Attachment settings(text.Attach txt file)
       mime={'type':'text', 'subtype':'comma-separated-values'}
       attach_file={'name':'test.txt', 'path':'./text.txt'}
 
       #Compose a message(There is an attachment)
       #msg = create_message(ADDRESS, to_addr, subject, body, mime, attach_file)
 
       #Message composition(No attachments)
       msg = create_message(ADDRESS, to_addr, subject, body)
 
       #Send
       send(ADDRESS, [to_addr], msg)

    

  time.sleep(SLEEPTIME)

The rest

sudo python sensor_push.py

An email will be sent to you (if the infrared sensor responds)

~ By the way ~

The subject is "Thieves! Fire! Murder!"

Postscript

~~ I have confirmed the operation, so if you want to be able to execute it automatically ~~

pi@raspberrypi:~$ crontab -e
#
#
@reboot python sensor_push.py
!!Caution!!#####

Before "@ reboot python sensor_push.py"

(Do not write "# @ reboot python sensor_push.py"!)

reference

[* Raspberry Pi *] It's summer! Let's make a cicada sound using a motion sensor [Send email easily with Gmail](http://make.bcde.jp/python/gmail%E3%81%A7%E7%B0%A1%E5%8D%98%E3%81%AB%E3%83 % A1% E3% 83% BC% E3% 83% AB% E9% 80% 81% E4% BF% A1 /)

Recommended Posts

Make a monitoring device with an infrared sensor
Make a GIF animation with folder monitoring
[Python] Make a game with Pyxel-Use an editor-
Make a fortune with Python
Make a fire with kdeplot
Let's make a GUI with python.
Make a sound with Jupyter notebook
Let's make a breakout with wxPython
Make a recommender system with python
Make a filter with a django template
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
Make a model iterator with PySide
Make Scrapy an exe with Pyinstaller
Make a nice graph with plotly
Make an audio interface controller with pyusb (2)
Make a video player with PySimpleGUI + OpenCV
Device monitoring with On-box Python in IOS-XE
Make an audio interface controller with pyusb (1)
Make a rare gacha simulator with Flask
I tried to make an open / close sensor (Twitter cooperation) with TWE-Lite-2525A
Make a Notebook Pipeline with Kedro + Papermill
Make a partially zoomed figure with matplotlib
Make a drawing quiz with kivy + PyTorch
Let's make a voice slowly with Python
Make a cascade classifier with google colaboratory
Let's make a simple language with PLY 1
Make a logic circuit with a perceptron (multilayer perceptron)
Make a Yes No Popup with Kivy
Make a wash-drying timer with a Raspberry Pi
Let's make a web framework with Python! (1)
Operate an oscilloscope with a Raspberry Pi
Let's make a tic-tac-toe AI with Pylearn 2
Make a desktop app with Python with Electron
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
Let's make an A to B conversion web application with Flask! From scratch ...
How to make an embedded Linux device driver (11)
A memorandum to make WebDAV only with nginx
How to make an embedded Linux device driver (8)
How to make an embedded Linux device driver (1)
Investment quest: Make a system trade with pyhton (2)
Make a Twitter trend bot with heroku + Python
How to make an embedded Linux device driver (4)
Make a simple pixel art generator with Flask
Investment quest: Make a system trade with pyhton (1)
How to make a dictionary with a hierarchical structure.
How to make an embedded Linux device driver (7)
I want to make a game with Python
How to make an embedded Linux device driver (2)
How to make an embedded Linux device driver (3)
Try to make a "cryptanalysis" cipher with Python
[Python] Make a simple maze game with Pyxel
Let's replace UWSC with Python (5) Let's make a Robot
How to make an embedded Linux device driver (6)
Try to make a dihedral group with Python
[Chat De Tornado] Make a chat using WebSocket with Tornado
Make holiday data into a data frame with pandas
Make a LINE WORKS bot with Amazon Lex
How to make an embedded Linux device driver (5)
How to make an embedded Linux device driver (10)