Recently I started learning raspberry pi and its different modules. Here I will tell you how to make a system that will shutdown all the systems in room after inactivity of few seconds. This is Raspberry PI Motion Sensor example.
In this Raspberry PI Motion Sensor example we are going to shutdown the computer systems that are running after a 100 seconds of inactivity.
Here what I did is used a motion sensor to detect if there is any activity, if there is no activity for a particular time period, my scripts issue a command to shutdown the systems. How I do it is below.
What all you need.
Raspberry PI 3 Model B [This is what I used.]
Motion sensor module HCSR-501
Few wires to Connect, A bread board would be awesome.
IP address of your systems to ssh.
First I connected the Motion sensor to the Raspberry Pi using the GPIO pins. There are three pins on Motion sensor which are VCC, GND, OUT.
VCC is connected to 5v supply on raspberry pi, out in connect to the pin in which you want the input, I connected it to GPIO13, pin 13.
GND is connected to GND of raspberry pi.
Connect a register to avoid any damage due to current. Connect the register between the OUT and GPIO13.
After this we need to do some coding for making our raspberry pi understand the input. Follow the below code.
Here I used library called Fabric which is used to run commands remotely using ssh and paramiko. Read about it more here.
Lets discuss what is done here in Raspberry PI Motion Sensor example code.
In the first two lines, RPi library is imported which will provide us options to use the pins via python and the time library for sleep function which we will use later.
In next line we imported the fabric and its api to run the commands on remote machine.
On fourth line we set the host. host is the IP of the machine we will ssh and shut down using fabric.
We need to make the IP of the systems static to always point to the same systems and avoid dynamic changing IPs.
In next two line we set the username and password to ssh into the machine.
Next we wrote a function to shutdown the remote machine.
In the main section, we have three variables current_state, total_inactive, pir_sensor.
current state is state of the sensor, total_inactive is time for which there is no activity, pir_sensor is the pin in which motion sensor is giving input to the raspberry pi.
Next we set the GPIO board and setup the pin number 13 as input pin.
Now we make an infinite loop inside which we keep on checking the current state of the sensors, if the state is inactive we add one to total_inactive else we reset it, once total_inactive is equal to 100 we call the shutdown.
This all what is done here in Raspberry PI Motion Sensor example.
Read below article for more details on Fabric.