def __init__(self, ledmatrix, pirpin, nomovementforseconds): logging.info('init motion') self.__Matrix = ledmatrix self.__delay = nomovementforseconds self.__pin = pirpin logging.info('set up sensor') self.__PIR = MotionSensor(self.__pin) logging.info('starting motion')
class PIR: def __init__(self, ledmatrix, pirpin, nomovementforseconds): logging.info('init motion') self.__Matrix = ledmatrix self.__delay = nomovementforseconds self.__pin = pirpin logging.info('set up sensor') self.__PIR = MotionSensor(self.__pin) logging.info('starting motion') # ------------------------------------------------------------------------- # wait_for_no_movement # Waits to see if there is movement within self.__delay seconds # If there is none, fades the matrix to black and stops it from being # updated. # Once movement is seen, fades the screen back on. # ------------------------------------------------------------------------- def wait_for_no_movement(self): logging.info('motionsensor') t = time.time() while True: nomovement = self.__PIR.wait_for_no_motion(10) if nomovement: logging.info('No movement') if (time.time() - t) >= self.__delay: logging.info('Turning off screen') self.__Matrix.set_draw_on_matrix(False) if self.__PIR.wait_for_motion(): t = time.time() logging.info('Turning on screen') self.__Matrix.set_draw_on_matrix(True) else: if self.__PIR.wait_for_motion(10): logging.info('Motion detected') t = time.time() else: logging.info('Motion detected') t = time.time()
#This doesn't work. WEnt to RPi.GPIO in Motion 2.py from gpiozero import MotionSensor, LED from signal import pause import time pir = MotionSensor(17) led = LED(4) def turnon(): led.on time.sleep(2) led.off pir.when_motion = turnon pir.when_no_motion = led.off pause()
from mailsender import MailSender from gpiozero import LED, MotionSensor #from gpiozero.pins.pigpio import PiGPIOFactory video_capture = cv2.VideoCapture(0) image = fr.load_image_file("harish.jpg") face_encoding = fr.face_encodings(image)[0] known_face_encondings = [face_encoding] known_face_names = ["harish"] #factory = PiGPIOFactory(host='192.168.225.135') #led = LED(17, pin_factory=factory) led = LED(17) pir = MotionSensor(4) logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) def alert_bot(update, context): update.message.reply_text('Alert bot activated') logger.info('Alert bot activated send to %s',update.message.chat.username) while True: try: if keyboard.is_pressed('ENTER'): # if pir.motion_detected: try: update.message.reply_text('Person alert!')
from gpiozero import MotionSensor from time import sleep motion_sensor = MotionSensor(4) while True: if motion_sensor.motion_detected: print('Dectected Motion!') sleep(2) else: print('No Motion Detected!') sleep(2)
#!/usr/bin/env python from gpiozero import MotionSensor, LED, Button from os import system from signal import pause m = MotionSensor(13) l1 = LED(19) def congrats(): # l1.blink() l1.on() system("happyBirthday") m.when_motion = congrats m.when_no_motion = l1.off pause()
from gpiozero import MotionSensor from gpiozero import LED from picamera import PiCamera from datetime import datetime from time import sleep pir = MotionSensor(21) camera = PiCamera() led = LED(14) while True: pir.wait_for_motion() t = datetime.now().strftime("%Y-%m-%d_%H.%M.%S") print("Mouvement détecté à", t, "!") led.on() video = '/home/pi/video_mouvements/' + t + ".h264" camera.start_recording(video) fileName = '/home/pi/video_mouvements/' + t + ".jpeg" camera.capture(fileName) pir.wait_for_no_motion() t = datetime.now().strftime("%Y-%m-%d_%H.%M.%S") print("Mouvement arrêté à", t, "!\n") led.off() camera.stop_recording()
#cool python file #Authors: Happy Hour Squad from gpiozero import MotionSensor import time #pir = MotionSensor(pin=4,queue_len=10,sample_rate=1.0,threshold=0.5,partial=False) pir2 = MotionSensor(4) def abc(): print("Motion detected") pir2.when_motion = abc while True: #if pir2.motion_detected: #print("Motion detected!") a = 3
from gpiozero import MotionSensor from time import sleep from picamera import PiCamera pir = MotionSensor(4) camera = PiCamera() while True: pir.wait_for_motion() camera.start_preview() pir.wait_for_no_motion() camera.stop_preview()
import emailSender from picamera import PiCamera from gpiozero import MotionSensor pir = MotionSensor(4) #monstion sensor connected to gpio 4 pir.wait_for_motion() #waiting to detect motion print("Motion Detected") camera = PiCamera() #camera object created and rotated camera.rotation = 180 image = camera.capture('/home/pi/webapp/static/selfie.jpg') #image capture filetoSend = "/home/pi/webapp/static/selfie.jpg" #path of image set to filetoSend send = emailSender.notify( filetoSend) #use emailSender's method notify to send email
import os from gpiozero import MotionSensor from time import sleep from signal import pause os.system( "echo none | sudo tee /sys/class/leds/led0/trigger | echo 1 | sudo tee /sys/class/leds/led0/brightness" ) print("Power LED disabled") motionSensor = MotionSensor(17) print("Motion Detection started") TIMEOUT = 30 STEP = 1 monitorEnabled = True stepCounter = 0 def handleMotion(): global TIMTEOUT, STEP, monitorEnabled, stepCounter while True: sleep(STEP) if motionSensor.motion_detected: stepCounter = 0 enableMonitor() monitorEnabled = True while stepCounter < TIMEOUT: if motionSensor.motion_detected:
# Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("city/devices/mds/" + devicename) client.publish("city/devices/mds/" + devicename, devicename + " connected") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic + " " + msg.payload.decode()) client = mqtt.Client(protocol=mqtt.MQTTv31) client.on_connect = on_connect #read from a file to get the ip of the server client.connect(siteConfig.ServerIp, 1883, 60) pir = MotionSensor(portId) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_start() try: while True: sleep(1) if pir.motion_detected: text = "Moition detected" client.publish("city/devices/mds/" + devicename, text) finally: client.loop_stop()
from gpiozero import LEDBoard, MotionSensor from gpiozero.pins.pigpio import PiGPIOFactory from signal import pause ips = ['192.168.1.3', '192.168.1.4', '192.168.1.5', '192.168.1.6'] remotes = [PiGPIOFactory(host=ip) for ip in ips] leds = LEDBoard(2, 3, 4, 5) # leds on this pi sensors = [MotionSensor(17, pin_factory=r) for r in remotes] # remote sensors for led, sensor in zip(leds, sensors): led.source = sensor pause()
else: errorCaptura = False # videoCapture.release() print("Termino captura de rostros exitosamente") return errorCaptura, NombreCarpetaPrueba, targetnames, NombresEtiquetas, video_capture, indexCamara, numeroMuestrasRostros, nombresAñadir numeroMuestrasRostros = 61 import validarRostro as vR indexCamara = 0 video_capture = 1.0 import recog as rg from gpiozero import MotionSensor import pickle pir = MotionSensor(4) # Numero de pin de raspberry llamada = False p, inputQueue, outputQueue = 0, 0, 0 estadoActualPasillo = False estadoActualPuerta = False nombre = "Sin reconocer" conexionExitosa, firebase, db, valores, _ = conectarFirebase() def funcionPrincipal(): video_capture = 1.0 movimientoPir = True primeraVez = True abriendo = "nada"
from gpiozero import MotionSensor, LED, Button from picamera import PiCamera from datetime import datetime from signal import pause from time import sleep ## Email specific libraries import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders ## Basic input / LED setups # pir = MotionSensor(4) # as in pin 7, GPIO4 pir = MotionSensor(27) # as in pin 13, GPIO27 (GPIO02 in the piz fig) myLed = LED(17) # pin 11 / GPIO17 # button = Button(20) button = Button(25) # PiZero GPIO25 pin 22 outside button.hold_time = 4 # secs ## Camera settings camera = PiCamera() camera.rotation = 270 # 180 for upside down camera camera.resolution = (1250, 950) ## setting from internet camera.framerate = 90 ## Email setup pwd = open("notMuch.dat", "r") pwd2 = pwd.read()
from gpiozero import MotionSensor from picamera import PiCamera from time import sleep import os camera = PiCamera() camera.resolution = (1280, 720) pir = MotionSensor(26, sample_rate=5, queue_len=3) while True: pir.wait_for_motion() print('Motion detected') list = os.listdir( 'ca1/static/images/detected') # dir is your directory path number_files = len(list) sleep(3) camera.capture('ca1/static/images/detected/captured' + str(number_files) + '.jpg') pir.wait_for_no_motion() sleep(10)
#uses the camera module to take a photo when the PIR sensor detects movement from picamera import PiCamera from time import sleep from gpiozero import MotionSensor camera = PiCamera() sensor=MotionSensor(4) n=0 camera.start_preview(alpha=200) sensor.wait_for_motion() n=n+1 camera.capture("/home/pi/Desktop/pir"+str(n)+".jpg") camera.stop_preview()
import time import os import sys import re import config_sensor as cfg from module_play import play_audio_file #----------- Do not modify below statements ------------------- try: print "[DEBUG] Starting PIR motion sensor..." # go to the default absolute path in order to read data file correctly os.chdir(cfg.folder) # motion sensor function probes the movement of people in front of entrance of the market. pir = MotionSensor(cfg.GPIO_PIN) count = 0 while True: print "[DEBUG] Sleeping..." # wait for until customer wil be appeared pir.wait_for_motion() count += 1 t = time.localtime() print ("################# Motion Detected! (%d) %d:%d:%d ##############################" \ % (count, t.tm_hour, t.tm_min, t.tm_sec)) #get time information with strftime fucntion for time acess and conversions #https://docs.python.org/2/library/time.html current_day = time.strftime("%Y%m%d") print "[DEBUG] Reading audio files..." #---------------------------------------------- Read audio file folder: start
from gpiozero import MotionSensor, LED, Buzzer, Button from time import sleep from signal import pause pir = MotionSensor(26) buzzer = Buzzer(19) button = Button(13) led1 = LED(17) led2 = LED(27) led3 = LED(22) led4 = LED(10) led5 = LED(9) led6 = LED(11) all = [led1,led2,led3,led4,led5,led6] def all_on(): buzzer.on() for i in all: i.on() sleep(0.1) def all_off(): buzzer.off() for i in all: i.off() while True: button.wait_for_press() print("SYSTEM ARMED YOU HAVE 5 SECONDS TO RUN AWAY") sleep(5)
class Detector(object): def __init__(self): # 4 = the pin on the Rasberry pi that the MotionSensor is connected to self.pir = MotionSensor(4, threshold=0.5) self.camera = PiCamera() self.source_photo = 'test.jpg' with open('new_user_credentials.csv', 'r') as input: csvreader = csv.DictReader(input) for row in csvreader: self.access_key_id = row['Access key ID'] self.secret_key = row['Secret access key'] def start(self): self.wait_for_motion() self.take_picture() self.wait_for_no_motion() photo = self.covert_img_to_bytes() results = self.aws_rekognition_image(photo) self.print_results(results) def wait_for_motion(self): self.pir.wait_for_no_motion() self.pir.wait_for_motion() print("Motion detect!") def wait_for_no_motion(self): self.pir.wait_for_no_motion() print("No Motion") def take_picture(self): self.camera.resolution = (1920, 1080) self.camera.rotation = 180 self.camera.start_preview() sleep(2) self.camera.capture(self.source_photo) self.camera.stop_preview() def stop_camera(self): self.camera.stop_recording() def start_camera(self): datename = "{0:%Y}-{0:%m}-{0:%d}:{0:%H}:{0:%M}:{0:%S}".format(datetime.now()) filename = str(datename) + "video.h264" self.camera.resolution = (640, 480) self.camera.rotation = 180 self.camera.start_recording(filename) def aws_rekognition_image(self, photo): client = boto3.client('rekognition', aws_access_key_id=self.access_key_id, aws_secret_access_key=self.secret_key, region_name='us-west-2') return client.detect_labels(Image={'Bytes': photo}) def covert_img_to_bytes(self): with open(self.source_photo, 'rb') as photo: return photo.read() def print_results(self, results): for each in results['Labels']: print(each['Name'] + ": " + str(each['Confidence']))
from time import time, sleep from gpiozero import MotionSensor # # measuring tool for checking payload on CPU # # for details see https://github.com/RPi-Distro/python-gpiozero/issues/227 # a note from the ticket: # In GPIO Zero this draws a constant 10-12% of CPU on the Raspberry PI Zero, # but with the older RPI.GPIO library and GPIO.add_event_detect CPU usage # barely goes above 1%. left = MotionSensor(20) # right = MotionSensor(21) last_update = time() last_reset = last_update def pir_change(): print("Change") global last_reset last_reset = time() left.when_motion = pir_change # right.when_motion = pir_change while True:
import datetime from gpiozero import MotionSensor import subprocess def takePhoto(): print("Take photo...") # cmd = ['ls', '-l'] # cmd = ['raspistill', '-o', out_file, '-w', '720', '-h', '720', '-hf', '-vf'] cmd = ['/bin/bash', '/home/pi/scripts/photo.sh', 'pir'] runProcessNoWait(cmd) def runProcessNoWait(cmd): process = subprocess.Popen(cmd) GPIO_PIN = 4 pir = MotionSensor(GPIO_PIN) while True: print("Wait for motion...") pir.wait_for_motion() print("You moved") takePhoto() print(datetime.datetime.utcnow()) print("Wait for no motion") pir.wait_for_no_motion()
# LED와 PIR 센서를 연결 # 움직임이 감지되면 동영상 녹화 시작 # 움직임이 없어지면 동영상 녹화 중지 # 파일명은 날짜_녹화시작시간.h264 # 화면 출력은 없음 # 녹화 중일 때는 LED ON import time from signal import pause from gpiozero import LED, MotionSensor import picamera import datetime motion = MotionSensor(20) led = LED(21) camera = picamera.PiCamera() camera.resolution = (640, 480) camera.vflip = True def start_record(): led.on() now = datetime.datetime.now() fname = now.strftime("%T%m%d_%H%M") + ".h264" print("motion") camera.start_recording(fname) def stop_record(): led.off()
from gpiozero import Robot, MotionSensor from signal import pause robot = Robot(left=(4, 14), right=(17, 18)) pir = MotionSensor(5) pir.when_motion = robot.forward pir.when_no_motion = robot.stop pause()
# # Monitor activity using the PIR sensor. # When movement is seen, start the full screen camera preview for 10 seconds # # Note: # - The PIR sensor seems a little flaky. It appears to pick up sporatic movement # even when there is none. This can cause the timeout threshold to be not met, # or cause a pre-mature in-office event to be triggered # - Research and testing seem to point to WiFi interference as the culprit. Turning off the # WiFi adapter on the Pi, or using longer cables and/or sheilding seems to help. # from gpiozero import MotionSensor from picamera import PiCamera from time import sleep # PIR sensor is attached to pin #4 on the GPIO pir = MotionSensor(24) # Camera does not use the GPIO; it has it's own dedicated interface camera = PiCamera() # Loop forever! while True: if pir.motion_detected: camera.start_preview() sleep(10) camera.stop_preview() # Don't need to constantly poll the PIR sensor sleep(0.025)
#!/usr/bin/env python3 from gpiozero import MotionSensor from vlc import MediaPlayer from signal import pause from sys import exit pir = MotionSensor(24) song_path = "../media/song.ogg" p = MediaPlayer(song_path) def toggle_playing(): global p if p.is_playing(): p.pause() else: p.play() # We need the next part to start the song again, as soon as the song finishes if p.get_time() == 0: p.stop() p = MediaPlayer(song_path) p.play() pir.when_motion = toggle_playing try: pause() except KeyboardInterrupt:
from gpiozero import MotionSensor import picamera import time # PIR sensor on GPIO pin 4 PIR_SENSOR_PIN = 4 # Minimum time between captures DELAY = 5 # Create pir and camera objects pir = MotionSensor(PIR_SENSOR_PIN) camera = picamera.PiCamera() while True: pir.wait_for_motion() timestring = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) print("Taking photo " + timestring) camera.capture('/home/pi/photo_' + timestring + '.jpg') time.sleep(DELAY)
status = subprocess.check_output(['vcgencmd', 'display_power']).decode('utf-8') return int(status[status.find('=') + 1:].strip()) subprocess.call(['vcgencmd', 'display_power', str(value)]) def reset(): logging.info('Motion detected') global timeout displayPower(1) timeout = 3600 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG) if displayPower(): timeout = 3600 else: timeout = -1 pir = MotionSensor(17) pir.when_motion = reset while True: if timeout == 0 and displayPower(): logging.info('No motion for 1 hour, turning off screen') displayPower(0) time.sleep(1) timeout -= 1
import time, socket, pickle, pymongo from gpiozero import MCP3008, Servo, MotionSensor import sys #sensors data divider = MCP3008(0) servo = Servo(17, 1) pir = MotionSensor(13) #input data location = "Compass One" close_state = True northCoordinates = 1.3924 eastCoordinates = 103.8954 #database objects client = pymongo.MongoClient( "mongodb+srv://newuser2:[email protected]/BinData?retryWrites=true&w=majority" ) mydb = client["BnnyBins"] mycol = mydb["BinData"] print("Starting Bunny Bin at", location) try: while True: print(divider.value) if pir.motion_detected: print("Motion detected!") if close_state:
class RaspiGpioSensor(MotionDetectorImpl): """ Class for wrapping python motion sensor """ def __init__(self, settings: RaspiGpioSensorSettings) -> None: super().__init__() LOGGER.info(f"Using motion sensor on pin {settings.gpio_pin_number}") self.__motion_sensor = GPIOMotionSensor( pin=settings.gpio_pin_number, queue_len=settings.queue_length, sample_rate=settings.sample_rate, threshold=settings.threshold) self.__settings = settings self.__motion_sensor.when_activated = self.__when_activated self.__motion_sensor.when_deactivated = self.__when_deactivated self.__handler: Optional[Callable[..., None]] = None self.__led: Optional[LED] = None if settings.led_gpio_pin_number > 0: self.__led = LED(settings.led_gpio_pin_number) # store activation status self._activated = False def register_handler(self, handler: Callable[..., None]) -> None: LOGGER.debug("Registering motion_sensor callback") self.__handler = handler def shutdown(self) -> None: LOGGER.info("Shutting down") # shutdown motion sensor thread and join self.__motion_sensor.close() @property def id(self) -> int: return self.__settings.gpio_pin_number def __when_activated(self) -> None: if self.disabled: LOGGER.debug("Sensor disabled, activation signal ignored") return self._activated = True LOGGER.debug("Sensor activated") if self.__led: self.__led.on() if self.__handler: self.__handler() def __when_deactivated(self) -> None: # when disabled, still check activation flag - in case of disable between activation cycle if self.disabled and not self._activated: LOGGER.debug("Sensor disabled, deactivation signal ignored") return self._activated = False LOGGER.debug("Sensor deactivated") if self.__led: self.__led.off()
from gpiozero import Button, LED, MotionSensor from time import sleep button = Button(3) led = LED(17) greenLed = LED(18) pir = MotionSensor(14) numberOfTimes = 0 encendido = False #button.when_pressed = led.on #button.when_released = led.off #pause() while True: if button.is_pressed: numberOfTimes += 1 sleep(0.5) if(numberOfTimes % 2 == 0): led.on() greenLed.off() encendido = False #print("Apagado!") else: led.off() encendido = True #print("Encendido!") if encendido:
import picamera # Camera functions import subprocess # Subprocess for livestream pipe import numpy as np # Use numpy for drawing overlay rectangles import time # Constants url = "rtmp://a.rtmp.youtube.com/live2/" # YouTube livestream url key = open("StreamKey.txt", "r").read() # YouTube livestream key catSearchTimeout = 5 # Cat search time after motion detected (seconds) catLostTimeout = 30 # Cat search time after target lost (seconds) # Command to start the livestream streamCmd = "ffmpeg -re -ar 44100 -ac 2 -acodec pcm_s16le -f s16le -ac 2 -i /dev/zero -f h264 -i - -vcodec copy -acodec aac -ab 128k -g 50 -strict experimental -f flv " + url + key # Hardware pin setup pir = MotionSensor(14) # Initializations classifier = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalcatface.xml") # Load cat image classifier camera = picamera.PiCamera(resolution=(800,480), framerate=25) # Init camera camera.hflip = True # Flip camera camera.vflip = True # Cat face detection funtion def catSearch(): camera.capture("temp.jpg") # Take an image img = cv2.imread("temp.jpg") # Open the image in the cv2 library gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert to grayscale faces = classifier.detectMultiScale(gray, 1.04, 3) # search for cat faces return faces # return list of face locations found
from gpiozero import MotionSensor PIR_PIN = 26 pir = MotionSensor(PIR_PIN) while True: if pir.motion_detected: print "motion detected" while pir.motion_detected: print "motion still detected" else: print "no motion!"
from gpiozero import LED, MotionSensor, LightSensor from gpiozero.tools import booleanized, all_values from signal import pause garden = LED(2) motion = MotionSensor(4) light = LightSensor(5) garden.source = all_values(booleanized(light, 0, 0.1), motion) pause()
global temp_readings temp_readings += 1 print("increasing count") def active_count_reset(): global temp_readings temp_readings = 0 print("resetting count") client = MongoClient("mongodb://*****:*****@ds145405.mlab.com:45405/breakthebuild?authMechanism=SCRAM-SHA-1") db = client["breakthebuild"] test_collection = db.test_collection sensor = MotionSensor(4) sensor.when_motion = active_count last = datetime.datetime.utcnow() while True: if datetime.datetime.utcnow() > last + datetime.timedelta(seconds = 30): print(temp_readings) if temp_readings >= 3: occupied = True else: occupied = False test_collection.insert({ "name" : "Lilly",
aio.send('led', c) # sending data to led feed aio.send('power', power) # sending data to power feed pir.wait_for_no_motion() # waiting for no motion aio.send('active', 0) green_led.off() # turning off all the street lights led1.off() led2.off() led3.off() led4.off() led5.off() print("Motion Stopped") c = 0 # initializing number of led turned on as 0 power = 0 # initializing power consumption as 0 green_led = LED(17) # GPIO 17 led1 = LED(12) # GPIO 12 led2 = LED(13) # GPIO 13 led3 = LED(19) # GPIO 19 led4 = LED(21) # GPIO 21 led5 = LED(26) # GPIO 26 pir = MotionSensor(4) # GPIO 4 green_led.off() led1.off() led2.off() led3.off() led4.off() led5.off() auto( ) # By default refering to the auto function for automatic switching on/off the street-lights
from gpiozero import MotionSensor from gpiozero import LED from signal import pause from time import sleep import random pir1 = MotionSensor(4) pir2 = MotionSensor(17) pir3 = MotionSensor(18) led1 = LED(27) # led2 = LED(4) from phue import Bridge import logging import thread logging.basicConfig() lightrunning = {1: False, 2: False, 3: False} b = Bridge('192.168.1.178', 'YxPYRWNawywC-sKHkjuRho7iOwMMSrn3di2ETF74') # Enter bridge IP here. lights = b.get_light_objects() # class light_status(): # # def __init__(self): #
#!/usr/bin/env python3 """ Caputures images triggered by motion sensor """ #import the necessary packages from gpiozero import MotionSensor from picamera import PiCamera from time import sleep from signal import pause IMAGE_PATH = '/home/pi/cat-repellent-water-gun/images' pir = MotionSensor(4, pull_up=True) camera = PiCamera() #start the camera camera.rotation = 180 camera.start_preview() img_num = 0 def take_photo(): global img_num img_num = img_num + 1 camera.capture(IMAGE_PATH + '/image_%s.jpg' % img_num) print('A photo has been taken') sleep(10)
from gpiozero import MotionSensor, LED pir = MotionSensor(26) led = LED(17) pir.when_motion = led.on pir.when_no_motion = led.off
from gpiozero import MotionSensor import paho.mqtt.client as paho import requests import Adafruit_DHT as ada import json import time pir = MotionSensor(4) class pirClients: def __init__(self, ID, broker, pub_topic, sub_topic, port=None): self.Id = ID self.broker = broker self.port = port self.pub_topic = pub_topic self.sub_topic = sub_topic self.client = paho.Client(ID) self.client.on_message = self.on_message self.client.on_connect = self.on_connect def startLoop(self): if self.port == None: self.client.connect(self.broker) else: self.client.connect(self.broker, self.port) self.client.loop_start() def stopLoop(self): self.client.disconnect() self.client.loop_stop()
client = mqtt.Client() client.loop_start() def take_photo(): timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = 'pic_' + timestamp + '.jpg' camera.capture(filename) fqp = os.getcwd() + '/' + filename scp = 'pi@' + ipaddr + ':' + fqp client.publish(topic, "photo taken: " + scp) def on_connect(client, userdata, flags, rc): client.subscribe(topic) def on_message(client, userdata, msg): command = msg.payload.decode("utf-8") if command == "take photo": take_photo() pir = MotionSensor(4) pir.when_motion = take_photo client.on_connect = on_connect client.on_message = on_message client.connect(server, 1883, 60) pause() client.loop_stop()
from gpiozero import MotionSensor from signal import pause import sys from time import sleep import LED_module import Figure_Movements pir = MotionSensor(12) def piron(): LED_module.light_LED() #call light_LED function when button is pressed Figure_Movements.move_figures_in_sequence() sleep(6) LED_module.dowse_LED() def piroff(): print('led.off') if __name__ == '__main__': while True: try: #green_led.on() #button.wait_for_press() pir.when_motion = piron #pause() except KeyboardInterrupt:
from gpiozero import MotionSensor from picamera import PiCamera from datetime import datetime import time import os if os.path.isfile('./authenticated')!=1: os.system("sudo grive --dry-run -a") f = open('authenticated','w') motion_timeout = 6; next_video_timeout = 0; camera = PiCamera() pir = MotionSensor(4) while True: pir.wait_for_motion() print 'motion detected' filename = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264") camfilename = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.jpg") camera.capture(camfilename) camera.start_recording(filename) pir.wait_for_no_motion(motion_timeout) camera.stop_recording() print 'motion ended' os.system("sudo grive -u -f") os.system("sudo rm *.jpg *.h264") time.sleep(next_video_timeout)
from gpiozero import MotionSensor import time PIN_PIR = 23 pir = MotionSensor(PIN_PIR) def callback_function(channel): print("Motion detected.") try: pir.when_motion = callback_function while (True): time.sleep(10) except KeyboardInterrupt: print("END")
args = parser.parse_args() output_dir = args.output_dir eventPostUrl = args.server cameraName = args.camera_name location = args.location print("Writing images to " + output_dir) print("Posting data to " + eventPostUrl) # IR Lamp MOSFET Setup GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) # Motion Sensor Setup pir = MotionSensor(4) # Camera Setup camera = picamera.PiCamera() camera.resolution = camera.MAX_RESOLUTION camera.led = False motionActive = False imageList = [] def getFileName(): return "/capture-" + datetime.now().strftime("%Y%m%d-%H%M%S.%f") + ".jpg" def getFilePath(fileName): return output_dir + "/" + fileName
} else continue recording/flow of lights """ from gpiozero import MotionSensor from picamera import PiCamera from time import sleep import signal import sys import RPi.GPIO as GPIO from subprocess import call #create objects that refer to a, #a motion sensor and the PiCamera pir = MotionSensor(4) camera = PiCamera() #image name i=0 # Setup GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.setup(18, GPIO.OUT) GPIO.setup(22, GPIO.OUT) def take_photo(): global i i = i + 1 filePath = "/home/pi/Desktop/projectpic/image_%s.jpg' %i" currentTime=datetime.now()