Magic Mirror – PIR Sensor – Update #3

Visits: 254

The idea of installing the motion detector is that it either turns the HDMI signal on or off. IF the motion detector does not detect any movement for 9 seconds (value that can be changed as required), it switches of the HDMI Signal. As soon as movement is registered again, it switches the signal on again. If movement is also registered during 60 seconds, the timer is reset to zero..

The pir sensor connected to raspberry pi with female-female jumper cable.

  • VCC to Pin 2
  • GND to Pin 6
  • OUT to Pin 12

And now the motion detector should switch the HDMI signal on or off. Two shell scripts are created for this. The first is created with command:

sudo nano /home/pi/magicmirror/monitor_on.sh

with following content:

vcgencmd display_power 1 > /dev/null

the second script with the command:

sudo nano /home/pi/magicmirror/monitor_on.sh

with following content:

vcgencmd display_power 0 > /dev/null

Now a python script.. Create this script with the command:

sudo nano /home/pi/magicmirror/pir_monitor_controller.py

with following content:

#!/usr/bin/env python

import sys
import time
import RPi.GPIO as io 
import subprocess

io.setmode(io.BOARD)
SHUTOFF_DELAY = 9
PIR_PIN=12

def main():
    io.setup(PIR_PIN, io.IN)
    turned_off = False
    last_motion_time = time.time()
    while True:
        if io.input(PIR_PIN):
            last_motion_time = time.time()
            sys.stdout.flush()
            if turned_off:
                turned_off = False
                turn_on()
        else:
            if not turned_off and time.time() > (last_motion_time + SHUTOFF_DELAY):
                turned_off = True
                turn_off()
            if not turned_off and time.time() > (last_motion_time + 1):
                time.sleep(.1)
def turn_on():
    subprocess.call("sh /home/pi/magicmirror/monitor_on.sh", shell=True)

def turn_off():
    subprocess.call("sh /home/pi/magicmirror/monitor_off.sh", shell=True)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        io.cleanup() 

Now service file… a service file has to be added so that this script is always executed when it is started. The command:

cd /lib/systemd/system/
sudo nano pir_monitor_controller.service

with the following content:

[Unit]      
Description=MagicMirror PIR Service       
After=multi-user.target       
                
[Service]       
Type=idle       
ExecStart=/usr/bin/python /home/pi/magicmirror/pir_monitor_controller.py > /home/pi/magicmirror/pir_monitor_controller.log 2>&1       
                
[Install]       
WantedBy=multi-user.target
sudo systemctl daemon-reload 
sudo systemctl enable pir_monitor_controller.service 
sudo systemctl start pir_monitor_controller.service

and Testing..