def main(): logging.basicConfig(format="[%(levelname)s %(name)s] %(message)s", level=logging.INFO) pir = MotionSensor(17) delay = timedelta(minutes=1) time_stamp = datetime.now() - delay def motion_detected(): nonlocal time_stamp if datetime.now() > (time_stamp + delay): logger.info("Motion detected!") filename = datetime.now().strftime("%m_%d_%Y__%H_%M_%S") camera = PiCamera() # camera.resolution = (1024, 768) # camera.start_preview() # # Camera warm-up time # time.sleep(2) # camera.capture('/home/pi/photos/{}.jpg'.format(filename)) # logger.info("Picture taken! Snap!") # time_stamp = datetime.now() camera.resolution = (640, 480) camera.start_recording('/home/pi/photos/{}.h264'.format(filename)) camera.wait_recording(30) camera.stop_recording() pir.when_motion = motion_detected logger.info("CatCam has started") pause()
def motion_light_thread(seconds, inf=False): pir = MotionSensor(19) #initialize motion sensor print(seconds) on = False def helper(): # when motion sensor activates os.system('./dist/lights on') return 0 end = time.time() + seconds pir.when_motion = helper #set helper to run when motion is detected if inf: while True: if exit_event.is_set(): os.system("./dist/lights off") break pir.wait_for_motion() time.sleep(1) else: while time.time() < end: if exit_event.is_set(): os.system("./dist/lights off") break pir.wait_for_motion() time.sleep(1) return 0
def __init__(self): for pin in cfg.motion.pins: pir = MotionSensor(pin, queue_len = cfg.motion.motion_queue_length) pir.when_motion = self._on_motion pir.when_no_motion = self._on_no_motion self.motionSensors.append(pir)
def start(self): pir = MotionSensor(self._pin) try: pir.when_motion = self.motion self.interrupted.wait() finally: pir.close() print('Shutdown gracefully.')
def _run_motion_sensor(self): """The threaded motion sensor object""" logging.info("Starting Motion Sensor Thread") pir = MotionSensor(self.motion_sensor_pin) pir.when_motion = self._motion_sensor pause()
def start_motion_detection(): """ Configure and start motion detection. """ print("Motion detection initalizing...") pir = MotionSensor(PIR_SENSOR_PIN) print("Motion sensor connected on PIN %s" % pir.pin) print("Waiting for motion sensor to settle") cam = PiCamera() cam.resolution = (800, 600) pir.when_motion = lambda x: take_photo(cam)
def main(): # now just write the code you would use in a real Raspberry Pi from Adafruit_CharLCD import Adafruit_CharLCD from gpiozero import Buzzer, LED, PWMLED, Button, DistanceSensor, LightSensor, MotionSensor from lirc import init, nextcode from py_irsend.irsend import send_once from time import sleep def show_sensor_values(): lcd.clear() lcd.message( "Distance: %.2fm\nLight: %d%%" % (distance_sensor.distance, light_sensor.value * 100) ) def send_infrared(): send_once("TV", ["KEY_4", "KEY_2", "KEY_OK"]) lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2) buzzer = Buzzer(16) led1 = LED(21) led2 = LED(22) led3 = LED(23) led4 = LED(24) led5 = PWMLED(25) led5.pulse() button1 = Button(11) button2 = Button(12) button3 = Button(13) button4 = Button(14) button1.when_pressed = led1.toggle button2.when_pressed = buzzer.on button2.when_released = buzzer.off button3.when_pressed = show_sensor_values button4.when_pressed = send_infrared distance_sensor = DistanceSensor(trigger=17, echo=18) light_sensor = LightSensor(8) motion_sensor = MotionSensor(27) motion_sensor.when_motion = led2.on motion_sensor.when_no_motion = led2.off init("default") while True: code = nextcode() if code != []: key = code[0] lcd.clear() lcd.message(key + "\nwas pressed!") sleep(0.2)
def monitor(): try: initCamera(camera) pir = MotionSensor(21) pir.when_motion = motion_start pir.when_no_motion = motion_stop while True: pir.wait_for_motion() except BaseException: print("ERROR: unhandled exception") finally: camera.close()
def __init__(self, websocket_server, sensors=None): """ Initiate PIR sensors. :param websocket_server: Websocket server :param sensors: list of objects like {'pin': 4} """ super(MotionSensorsThread, self).__init__() print('Initializing motion sensors thread') self.websocket_server = websocket_server self.should_run = True self.sensors = sensors self._init_sensors_state_dict() for s in self.sensors: s['instance'] = MotionSensor(s.get('pin')) s['instance'].when_motion = lambda instance: self._detect_event_for( instance)
def main(): args = parse_args() if args.debug: log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) global timer timer = Timer(args.duration, exit_application) timer.start() log.debug( f"{datetime.datetime.now()}: Motion timer is set for {args.duration} seconds" ) pir = MotionSensor(pin=17) pir.when_motion = lambda: motion_detected() try: while True: pir.wait_for_motion() except KeyboardInterrupt: log.error("Leaving...")
def monitor(words): times = get_time_interval(words) #for monitoring for a set time total_seconds = 0 if (times[0] > 0): #seconds total_seconds += times[0] if (times[1] > 0): #minutes total_seconds += times[1] * 60 if (times[2] > 0): #hours total_seconds += times[2] * 60 * 60 print(str(total_seconds)) # for debugging if (total_seconds == 0): total_seconds = 10 pir = MotionSensor(MOT_SENSOR) #initialize motion sensor def helper(): # when motion sensor activates os.system('raspivid -o ./monitor_capture/temp' + str(datetime.now().strftime("%H:%M:%S")) + '.h264 -t 10000') return 0 pir.when_motion = helper #set helper to run when motion is detected mouth.speak_aloud("Monitor Mode Active") timeout = time.time() + total_seconds while time.time() < timeout: pir.wait_for_motion(total_seconds) return "Leaving Monitor Mode"
entr_request() def exit_sensor_triggered(): exit_request() def emergency_button_held(): emergency_open() def entr_side_clear(): entr_person_passed() entrTopSensor.when_motion = entr_sensor_triggered exitTopSensor.when_motion = exit_sensor_triggered entrSideSensor.when_no_motion = None exitSideSensor.when_no_motion = None openSwitch.when_held = emergency_button_held forceOpen = False sensorClear = False # Define other methods def open_gate(entering): # to be completed global servo if entering: # assumes that entering people need the servo to go to max servo.max() else: servo.min()
#!/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, LED from subprocess import call from datetime import datetime from signal import pause import time # Set pin for motion sensor pir = MotionSensor(23) #GPIO, as in pin 16 # Define camera action def fartSound(): ## Play wav call(["aplay", "-i", "/home/joelpione/Music/Wet_fart.wav"]) # When motion is detected, snap photo pir.when_motion = fartSound pause()
#set your email message body = 'Hello Philip. I have detected movement inside your room.' msg = MIMEText(body) #set send and recipient msg['From'] = from_email_addr msg['To'] = to_email_addr #set your email subject msg['Subject'] = 'MOTION DETECTED! MOTION DETECTED! ' #connect to server and send email #edit this line with your provider's SMTP server details server = smtplib.SMTP('smtp.gmail.com', 587) #comment out this line if your provider doesn't use TLS server.starttls() server.login(from_email_addr, from_email_password) server.sendmail(from_email_addr, to_email_addr, msg.as_string()) server.quit() email_sent = True led_triggered.on() print('Email Sent') #assign a function that runs when the button is pressed button.when_pressed = arm_motion_sensor #assign a function that runs when motion is detected pir.when_motion = send_email pause()
global motionActive global imageList motionActive = False # Switch off lamp GPIO.output(17,GPIO.LOW) postImages(imageList) imageList = [] def postImages(imageList): if len(imageList) > 0: data = {} data['cameraName'] = cameraName data['cameraLocation'] = location data['date'] = datetime.now().isoformat() data['images'] = imageList json_data = json.dumps(data).encode('utf8') req = urllib.request.Request(eventPostUrl, data=json_data, headers={'content-type': 'application/json'}) response = urllib.request.urlopen(req) pir.when_motion = motionDetected pir.when_no_motion = noMotionDetected while True: pir.wait_for_motion(0.1) if motionActive: capturePiImage()
def motion_detected(): if debug: print("{}: Motion detected...".format(datetime.datetime.now())) turn_lights_on() def parse_args(): parser = argparse.ArgumentParser( description="Script to control kitchen sink lights.") parser.add_argument("--debug", action="store_true", help="Enable debug mode") return parser.parse_args() if __name__ == "__main__": args = parse_args() debug = args.debug pir = MotionSensor(pin=14) pir.when_motion = lambda: motion_detected() turn_lights_off() try: while True: pir.wait_for_motion() except KeyboardInterrupt: print("Leaving...")
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()
# send movie recording to blob logging.debug("uploading video {}".format(mov_filename)) with open(mov_filename, 'rb') as f: content = f.read() file_name = os.path.join("videos/scoring", os.path.basename(mov_filename)) logging.debug("uploading video to {}".format(file_name)) iot_client.upload_blob_async(file_name, content, len(content), blob_upload_callback, DEBUG) logging.debug("Deleting files") os.remove(jpg_filename) os.remove(mov_filename) else: # clear out image and recording logging.debug("Deleting files") os.remove(jpg_filename) os.remove(mov_filename) except Exception as e: logging.debug('Encountered exception: {}\n Carrying on...'.format(e)) # finally: # # stop video recording # camera.stop_preview() # camera.stop_recording() pir.when_motion = motion_detected pause()
from gpiozero import Robot, Motor, MotionSensor from signal import pause robot = Robot(left=Motor(4, 14), right=Motor(17, 18)) pir = MotionSensor(5) pir.when_motion = robot.forward pir.when_no_motion = robot.stop pause()
from gpiozero import MotionSensor from signal import pause from picamera import PiCamera from datetime import datetime from signal import pause # The PIR sensor lead is connected to GPIO27 = Board 13 sensor_pin = 27 # This set the MotionSensor with default settings with pull down as per original code pir = MotionSensor(sensor_pin) camera = PiCamera() def capture(): timestamp = datetime.now().strftime("%Y%m%dT%H%M%S-%f") camera.capture('/images/img-%s.png' % timestamp) pir.when_motion = capture pause()
#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()
#!/usr/bin/env python # Import libraries from gpiozero import MotionSensor, LED from gpiozero import MCP3008 from signal import pause from time import sleep # Variables pir = MotionSensor(4) light = LED(16) #adc = MCP3008(channel=0) # Functions def convert_temp(gen): for value in gen: yield (value * 3.3 - 0.5) * 100 # Program #while True: pir.when_motion = light.on pir.when_no_motion = light.off #temp = convert_temp(adc.values) #print('The temperature is', temp, 'C') #sleep(1) pause()
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", "location" : "3.L", "occupied" : occupied,
from time import sleep from gpiozero import MotionSensor, LED from robot import RaspberryRobot from signal import pause pir = MotionSensor(14) robot = RaspberryRobot() def dance(): robot.backward() sleep(5) robot.right() sleep(5) robot.stop() def print_no_motion(): print("no_motion") pir.when_motion = dance pir.when_no_motion = robot.stop pause()
sleep(0.5) lights[12].on = True lights[12].brightness = 215 lights[12].hue = 32768 sleep(0.5) lights[13].on = True lights[13].brightness = 215 lights[13].hue = 32768 sleep(0.5) lights[14].on = True lights[14].brightness = 215 lights[14].hue = 32768 sleep(0.5) pir1.when_motion = mot1 pir2.when_motion = mot2 pir3.when_motion = mot3 while True: for y in range(26): for x in range(15): lights[x].on = True lights[x].brightness = 15 sleep(0.2) lights[x].brightness = 215 lights[x].hue = 1500 * y + 15000 print("x: " + str(x)) print("y: " + str(y)) print("hue: " + str(1500 * y + 15000)) sleep(0.2)
from gpiozero import MotionSensor from signal import pause pir = MotionSensor(12) #led = LED(16) def piron(): print('led.on') def piroff(): print('led.off') pir.when_motion = piron pir.when_no_motion = piroff 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) pir.when_motion = all_on pir.when_no_motion = all_off
from gpiozero import MotionSensor, LED pir = MotionSensor(26) led = LED(17) pir.when_motion = led.on pir.when_no_motion = led.off
#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
help="The length of the queue used to store values read from the sensor. (1 = disabled)", type=int, default=1) parser.add_argument("-w", "--sample_rate", help="The number of values to read from the device " + "(and append to the internal queue) per second", type=float, default=100) parser.add_argument("-x", "--threshold", help="When the mean of all values in the internal queue rises above this value, " + "the sensor will be considered active by the is_active property, " + "and all appropriate events will be fired", type=float, default=0.5) parser.add_argument("-s", "--shadow_var", help="Shadow variable", required=True) parser.add_argument("-y", "--high_value", help="high value", default=1) parser.add_argument("-z", "--low_value", help="low value", default=0) parser.add_argument("-o", "--low_topic", nargs='*', help="Low topic") args = parser.parse_args() logging.basicConfig(filename=awsiot.LOG_FILE, level=args.log_level, format=awsiot.LOG_FORMAT) publisher = awsiot.MQTT(args.endpoint, args.rootCA, args.cert, args.key) pir = MotionSensor(args.pin, queue_len=args.queue_len, sample_rate=args.sample_rate, threshold=args.threshold) pir.when_motion = motion pir.when_no_motion = no_motion pause()
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()
PIR pins: 5V, GND, GPIO14 LED : GND, GPIO15 Buzzer : GND, GPIO27 ''') pir = MotionSensor(14) led = LED(15) buzzer = Buzzer(27) def when_motion(): print("Motion detected") led.on() buzzer.beep() def when_no_motion(): print("Motion stopped") led.off() buzzer.off() pir.when_motion = when_motion pir.when_no_motion = when_no_motion print("Running...") pause() #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - print("Done.") #//EOF
# # 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: if time() - last_update >= 10: print("Idle %d secs" % (time() - last_reset)) last_update = time() sleep(0.02)
from gpiozero import MotionSensor, LED from signal import pause pir = MotionSensor(4) led = LED(17) pir.when_motion = led.on pir.when_no_motion = led.off pause()
from time import sleep cam = PiCamera() pir = MotionSensor(21) led1 = LED(4) led2 = LED(17) n = 0 def name(): return 'photo-%03d.jpg'%n def rafale(): global n led2.on() i = 0 while i<10: led1.on() cam.capture('/home/pi/Desktop/photos/%s'%name()) print('picture taken') n=n+1 i=i+1 sleep(0.5) led1.off() sleep(0.5) led2.off() pir.when_motion = rafale pause()
from gpiozero import MotionSensor from gpiozero import LED from time import sleep def handle_motion(): print("Motion detected!") led.on() sleep(1) led.off() sleep(1) led = LED(17) pir = MotionSensor(18) print(pir.pin.number) pir.when_motion = handle_motion while (True): sleep(1) #pir.wait_for_motion(); # handle_motion();
server.close() print("Email sent!") except: print("Email wasn't sent!") #main function while True: # Define the motion sensor, button pressed, and reed swtich motion.when_motion = motionDetect pushButton.when_pressed = systemArm reedSwitch.when_released = reedSwitch #When armed with no motion and reed switch if armed == True and motion.value == 0 and reedSwitch.value == 1: alarmled.off() armledstate = False
from gpiozero import MotionSensor, LED from subprocess import call from picamera import PiCamera from datetime import datetime from signal import pause # Set pin for motion sensor pir = MotionSensor(4) # as in pin 7 camera = PiCamera() camera.rotation = 180 # for upside down camera camera.resolution = (1250, 950) ## setting from internet camera.framerate = 90 # Define camera action def takePic(): ## Photo business tstamp = datetime.now().isoformat() camera.capture('/home/jen/testPics/%s.jpg' % tstamp) ## Play wav call(["aplay", "-i", "/home/jen/camera-shutter-click-02.wav"]) # When motion is detected, snap photo pir.when_motion = takePic pause()
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()