check this for pinlayout : https://kjetiliot.blogspot.no/p/raspberry-pi.html
Install dependencies:
- sudo apt-get install python-pip
- pip install paho-mqtt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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); | |
Make the script executable
sudo chmod a+x filenameAdd 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'