Saturday, 31 December 2016

PIR Raspberry PI sensor

Using a HC-SR505(generic PIR) module to detect motion for your home automastion is pretty straigh forward. For my setup i connected pin 2 to 5v pin 12 to signal pin 14 to GND
check this for pinlayout : https://kjetiliot.blogspot.no/p/raspberry-pi.html

Install dependencies:

  1. sudo apt-get install python-pip
  2. pip install paho-mqtt
Code:
#!/usr/bin/python
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
import time
sensor = 18
mqttserver = "192.168.1.194"
mqttusr = "mqtt"
mqttpsw = "mqtt"
mqtttopic = "home/office/presence"
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)
previous_state = False
current_state = False
while True:
time.sleep(0.1)
previous_state = current_state
current_state = GPIO.input(sensor)
if current_state != previous_state:
new_state = "HIGH" if current_state else "LOW"
mqttc = mqtt.Client()
mqttc.username_pw_set(mqttusr, mqttpsw)
mqttc.connect("192.168.1.194", 1883,60)
if new_state == "HIGH":
mqttc.publish(mqtttopic,1);
else:
mqttc.publish(mqtttopic,0);
view raw gistfile1.txt hosted with ❤ by GitHub

Make the script executable

sudo chmod a+x filename

Add script to crontab

To start the script to automaticly run at at startup run the command : sudo crontab -e and add the following line(edit the path to fit your filename and path) : @reboot sudo python /home/pi/pirsensor.py & You can now reboot and check everything is working.
You can test that the pir is publishing correctly by subscribint to the mqtt topic you used in the pir sensor python script mosquitto_sub -v -t 'home/office/presence'

Parts: