Skip to content

Instantly share code, notes, and snippets.

@bphermansson
Created March 26, 2017 06:41
Show Gist options
  • Save bphermansson/7e48deab0f4d4d9c11040a9cf331aa8b to your computer and use it in GitHub Desktop.
Save bphermansson/7e48deab0f4d4d9c11040a9cf331aa8b to your computer and use it in GitHub Desktop.
Uses a Raspberry Pi and a PIR (motion) sensor. Sends Mqtt messages when motion is detected.
#!/usr/bin/env python
from time import time, sleep
import datetime
import os # For running external commands
import RPi.GPIO as GPIO
import urlparse
import paho.mqtt.client as paho
# Time to wait (in seconds)
ttw=60*10
cttw=ttw
# Setup Gpio
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(13, GPIO.IN) #Output from PIR motion sensor connected to pin 13
# Mqtt
#mqttc = mosquitto.Mosquitto()
mqttc = paho.Client()
url_str = 'mqtt://192.168.1.79:1883'
url = urlparse.urlparse(url_str)
mqttc.username_pw_set("user", "password")
def sendmqtt(mess):
#print "Send mqtt"
now = datetime.datetime.now()
mqttc.connect(url.hostname, url.port)
mqttc.publish("pir/hallway", str(now) + mess)
while True:
i=GPIO.input(13)
if i==0: #When output from motion sensor is LOW, no movement
cttw-=1
#print cttw
if cttw==0: # Counter has reached zero
#print "Counter is 0"
sendmqtt("Timeout")
cttw=ttw # Reset counter
elif i==1: #When output from motion sensor is HIGH, movement detected
#print "Motion detected"
cttw=ttw # Reset counter
sendmqtt("Motion!")
sleep(1) # Dont send to many messages
sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment