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()
from gpiozero import MotionSensor pir = MotionSensor(13) print("Ready...") while True: intruder = pir.wait_for_motion(timeout=2) if intruder: print("Intruder!!") pir.wait_for_no_motion() print("Ready...")
#------------------------------------------------------------------------------- # PIR Test Bed #------------------------------------------------------------------------------- #PIR output connected to GPIO4 (Physical Pin 7) from gpiozero import MotionSensor pir = MotionSensor(4) pir.wait_for_motion() print("Motion Detected!!")
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()
#led_red = LED (13) lcd1 = use_lcd.MyLCD() camera = picamera.PiCamera() camera.ISO = 500 #camera.shutter=500 camera.rotation = 180 camera.resolution = (640, 480) #with Image(blob=file_data) as image: #wand.display.display(IMAGE) lcd1.center_str(text_in1='Alarm system', text_in2='Start') x = 0 while True: while pir.wait_for_motion(): alarm_text = 'Detect #%d' % x lcd1.left_str(text_in1=alarm_text, to=2) print("detect", x) filename = '/home/guy/image%d.jpg' % x camera.capture(filename) #image = Image.open(filename) #image.show() subprocess.run(filename) #os.startfile(filename) x += 1 #buz.on() #led_red.on() #sleep(0.05) #buz.off()
def sense(): print("Sensing...") pir = MotionSensor(4) if (pir.wait_for_motion()): print("Motion detected!") return 1
print("false") signal = False url = "http://" + ip + ":" + port + "/catalog/refresh?ID=RPS02" pir_client.publish( json.dumps({ 'bn': "RPS02", 'e': [{ 'n': 'pir', 'u': None, 't': time.time(), 'v': signal }] })) while (pir.wait_for_motion(2)): signal = True url = "http://" + ip + ":" + port + "/catalog/refresh?ID=RPS02" pir_client.publish( json.dumps({ 'bn': "RPS02", 'e': [{ 'n': 'pir', 'u': None, 't': time.time(), 'v': signal }] })) print("true")
from gpiozero import MotionSensor from picamera import PiCamera import datetime pir = MotionSensor(4) # creates motion sensor on gpio 4 camera = PiCamera() now = datetime.datetime.now() # gets current date and time filename = "intruder_" + str(now).replace(" ", "_") + ".mp4" # creates filename that changes based on date and time while True: pir.wait_for_motion() # waits for motion sensor to be triggered print("Motion detected") camera.start_recording(filename) # starts new recording with filename pir.wait_for_no_motion() # waits for motion to stop camera.stop_preview() # stops recording
desired_3 = 180 GPIO.setup(servoPin, GPIO.OUT) GPIO.setup(servoPin_1, GPIO.OUT) pwm = GPIO.PWM(servoPin, 50) pwm_1 = GPIO.PWM(servoPin_1, 50) pir = MotionSensor(24) camera = PiCamera() print("Developement of an Embeeded Vision Based Fruit Sorting Machine") print("By: Clary Norman (2017141960)") time.sleep(4) os.system('cls') print("") print("PLace the fruit") while True: if pir.wait_for_motion(): #object is near print("Fruit detected..") rawCapture = PiRGBArray(camera) time.sleep(1) camera.capture(rawCapture, format='bgr') time.sleep(5) I = rawCapture.array from detectOrangeFunc import detectOrange [y, x, z, r] = detectOrange(I) from detectAppleFunc import detectApple [y1, x1, z1, t] = detectApple(I) ## Classification: print("") print("number of pixels for orange: ")
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
def test_motionsensor(): print('Testing motion sensor...') pir = MotionSensor(MOTION_PIN, sample_rate=5, queue_len=1) print('Activate the motion sensor') pir.wait_for_motion() return True
import picamera.array import shutil import subprocess import sys from fractions import Fraction pir = MotionSensor(4) # Make the reference object for the PIR motion sensor rootFolder = "/home/pi/Desktop/" # Define the root folder for convenience later tempFolder = rootFolder + "temp" # Define the reference folder for placement of images and videos #print(tempFolder) while True: pir.wait_for_motion() # Using the PIR sensor, wait for motion before continuing #print("Motion Detected") # Print a notice to the console for debugging # Turn on IR array here # Create date timestamps for files timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") # method calls date/time cast str$ timestamp_jpg = tempFolder + "/" + timestamp + ".jpg" timestamp_mp4 = tempFolder + "/" + timestamp + ".mp4" # Capture image print("Capturing image...") subprocess.call(["raspistill", "-t", "1", "-n", "-o", timestamp_jpg]) # Move image to 'images' folder os.rename(timestamp_jpg, timestamp_jpg.replace("temp", "images"))
class pyTrigger: def __init__(self, fromAddr, toAddr, pwd, m=4): self.fromAddr = fromAddr self.toAddr = toAddr self.pwd = pwd self.motionsense = m self.pir = MotionSensor(self.motionsense) self.camera = picamera.PiCamera() def getFileName(self): return datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S.jpg") def compileMessage(self, filename): toAddr = self.toAddr fromAddr = self.fromAddr pwd = self.pwd msg = MIMEMultipart() # storing the senders email address msg['From'] = fromAddr # storing the receivers email address msg['To'] = toAddr # storing the subject msg['Subject'] = f"Motion Detector Alert, image captured: {filename}" # string to store the body of the mail body = "This is an auto-generated message prompted by a motion detection" # attach the body with the msg instance msg.attach(MIMEText(body, 'plain')) # open the file to be sent # filename = "File_name_with_extension" attachment = open(filename, "rb") # instance of MIMEBase and named as p p = MIMEBase('application', 'octet-stream') # To change the payload into encoded form p.set_payload((attachment).read()) # encode into base64 encoders.encode_base64(p) p.add_header('Content-Disposition', f"attachment; filename= {filename}") # attach the instance 'p' to instance 'msg' msg.attach(p) # creates SMTP session s = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security s.starttls() # Authentication## You must enter your password here, or recode. I understand the risks of a hardcoded password :( s.login(fromAddr, pwd) # Converts the Multipart msg into a string text = msg.as_string() # sending the mail s.sendmail(fromAddr, toAddr, text) s.quit() print(f"motion captured {filename} image emailed to {toAddr}. More reports to follow.") time.sleep(10) def cameraCapture(self): # waiting for motion self.pir.wait_for_motion() if self.pir.motion_detected: # text to print for good feelings print("intruder detected") # set file name now that detection has happened filename = self.getFileName() # these steps for picamera self.camera.resolution = (2592, 1944) # for debugging # camera.start_preview() time.sleep(0.1) self.camera.capture(filename) print("intruder image saved " + filename) return filename def run(self): # warm up and IR baseline print("warming up") time.sleep(60) print("warm up complete") while True: image = self.cameraCapture() self.compileMessage(image)
def setup_steps(): global user global visual1 global visual2 global baseURL # Setup PIR & wait for motion. pir = MotionSensor(4) pir.wait_for_motion() # Setup Bluetooth discovery print('Performing Bluetooth scan...') b = (0, 0, 255) #blue y = (255, 255, 0) #yellow #Draw Bluetooth symbol on Sense Hat to let user know detection is running btd = [ y, y, y, b, y, y, y, y, y, y, y, b, b, y, y, y, y, b, y, b, y, b, y, y, y, y, b, b, b, y, y, y, y, y, y, b, y, y, y, y, y, y, b, b, b, y, y, y, y, b, y, b, y, b, y, y, y, y, y, b, b, y, y, y ] sense.set_pixels(btd) nearby_phones = discover_devices(lookup_names=True) sense.clear() # List of MAC addresses and associated user details - name, Thingspeak channel, Matlab visualisations known_phones = { '88:BD:45:06:xx:xx': { 'uname': 'Seamus', 'api': 'xxxxxxxxxxxxxxx1', 'mvis1': '37xxxx', 'mvis2': '37xxxx' }, '12:23:34:45:xx:xx': { 'uname': 'Tracy', 'api': 'xxxxxxxxxxxxxxx2', 'mvis1': '37xxxx', 'mvis2': '37xxxx' } } phones = [] for addr, name in nearby_phones: phones.append(addr) for addr in phones: if addr in known_phones: user = known_phones[addr]['uname'] print(user + " has logged on") baseURL = 'https://api.thingspeak.com/update?api_key=%s' % known_phones[ addr]['api'] visual1 = "https://thingspeak.com/apps/matlab_visualizations/%s" % known_phones[ addr]['mvis1'] visual2 = "https://thingspeak.com/apps/matlab_visualizations/%s" % known_phones[ addr]['mvis2'] if user == '': print('No user identified. Please check Bluetooth and try again') sense.show_message("No known user found!", text_colour=y, back_colour=b, scroll_speed=0.05) sense.clear() exit() sense.show_message("Hello " + user, text_colour=y, back_colour=b, scroll_speed=0.05) sense.clear()
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 gpiozero import MotionSensor #impport module to use PIR motion sensor from picamera import PiCamera #impport module to use the camera module from datetime import datetime pir =MotionSensor(4) #PIR sensor connected to pin GPIO 4 today=datetime.now() #takes the current time time = int(today.strftime("%H")) #extract only hour from current time while time>8 and time<17 : #time range to capture pir.wait_for_motion() #Upto motion print("MOtion Detected") today=datetime.now() #takes the current time time = int(today.strftime("%H")) #extract only hour from current time camera = PiCamera() #Create a PiCamera Object camera.rotation=180 #Rotate the image if needed camera.capture('/home/pi/Desktop/image/'+str(today) + '.png') #Capture the image and store it camera.close() #Close the Camera
class Motion(): ERROR = -1 LISTEN = 1 CONNECTED = 2 STOP = 3 SIG_NORMAL = 0 SIG_STOP = 1 SIG_DISCONNECT = 2 def __init__(self, config): self.camera_port = config['camera']['listen_port'] self.bot_port = config['bot']['listen_port'] self.ip = '127.0.0.1' self.port = config['motion']['listen_port'] self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.motion_pin = config['motion']['pir_pin'] self.interval = config['motion']['interval'] self.timestamp = None self.time_start = datetime.time( hour=config['motion']['time_start'][0], minute=config['motion']['time_start'][1]) self.time_end = datetime.time(hour=config['motion']['time_end'][0], minute=config['motion']['time_end'][1]) self.pir = MotionSensor(self.motion_pin) def send_udp(self, msg, port): payload = json.dumps(msg) self.udp_socket.sendto(payload.encode(), ('127.0.0.1', port)) def run(self): logging.info('Motion thread started') while True: self.pir.wait_for_motion() current_time = time.time() if self.timestamp is not None: if current_time - self.timestamp < self.interval: continue now_time = datetime.datetime.now().time() if self.time_start < self.time_end: if now_time < self.time_start: continue if now_time > self.time_end: continue else: if now_time < self.time_start and now_time > self.time_end: continue print('motion detected') self.timestamp = current_time date_str = datetime.datetime.now().strftime('%Y-%m-%d') time_str = datetime.datetime.now().strftime('%H-%M-%S') self.send_udp({'cmd': 'take_photo', 'count': 1}, self.camera_port) self.send_udp( { 'cmd': 'send_msg', 'date': date_str, 'time': time_str }, self.bot_port) logging.info('motion detected') self.pir.wait_for_no_motion()
from gpiozero import MotionSensor pir = MotionSensor(17) if pir.wait_for_motion(4): print("Motion detected!") else: print("no motion")
from email.mime.base import MIMEBase from email.mime.text import MIMEText import email.encoders import smtplib #****************Setup******************* pir_1 = MotionSensor(4) camera = PiCamera() #****************Heart of the Code*********** while True: # WAIT FOR MOTION AND THEN RECORD VIDEO pir_1.wait_for_motion() now = datetime.now() filename = "{0:%d}-{0:%m}-{0:%Y}.h264".format(now) print("Intruder Alert!") camera.start_recording(filename) pir_1.wait_for_no_motion() print("Deactivated!") camera.stop_recording() # EMAIL SETUP print("PREPARTING EMAIL") stamp = "{0:%d}-{0:%m}-{0:%Y}.h264".format(now) msg = MIMEMultipart() msg["subject"] = stamp msg["from"] = "*****@*****.**" msg["to"] = "*****@*****.**"
from picamera import PiCamera from gpiozero import MotionSensor from gpiozero import LED from time import sleep camera = PiCamera() sensor = MotionSensor(4) cameraNightMode = LED(19) cameraNightMode.off() for i in range(2): sensor.wait_for_motion() print("minnie") # camera.start_recording('/home/pi/Desktop/minnieVideo' + i + '.h264') # sleep(10) # camera.stop_recording()
def main(): # Load the settings settings.init() # Wait for network to come up util.waitForNetUp(settings.botUser) # Process the command line arguments util.processArgs() # If we aren't running as a service and the service is already running, we'll get a conflict, so quit if not settings.service and util.checkService(): logMessage('Service running - exiting ') exit() # Setup the logging util.setupLog() # If we aren't running in test mode, then setup for Slack communication if not settings.testmode: util.setupSlack(settings.slackChannel) util.postSlackMessage(':snowflake: ' + settings.botUser + ' is up', None, settings.botEmoji, settings.botUser, settings.slackChannel2) # Mount the network share util.mountShare() # Tidy up the temporary capture store in case we left it in a mess # util.tidyupTempStore() util.storeVideo() # PIR is on pin 18 pir = MotionSensor(18) logMessage('Starting - Video seconds: ' + str(settings.recordtime) + '; Still seconds: ' + str(settings.stillSeconds) + '; Test mode: ' + str(settings.testmode) + '; Service: ' + str(settings.service)) # Wait an initial duration to allow PIR to settle time.sleep(10) # Camera time ! with picamera.PiCamera() as cam: # Set the camera up timeFM = '%H:%M:%S.%f' cam.rotation = settings.camRotation cam.resolution = settings.camResolution cam.annotate_background = picamera.Color('black') # Record when last motion detected global motionStart pir.when_motion = incrementTimer # Keep going for ever while True: # Wait for motion.... logMessage('Waiting for motion') pir.wait_for_motion() logMessage('Motion detected recording for ' + str(settings.recordtime) + ' seconds') # If not in test mode, send a slack alert - Potential hedgehog! if not settings.testmode: util.postThreadedSlackMessage('Hedgehog alert :hedgehog:', None, settings.botEmoji, settings.botUser) # Setup our filenames, so all capture files are consistently named output_basefilename = "{}".format( datetime.now().strftime('%Y%m%d-%H%M%S')) recordVideo = settings.rootPath + 'videos/' + output_basefilename + '.h264' recordStill = settings.rootPath + 'videos/' + output_basefilename + '.jpg' # Start recording cam.start_recording(recordVideo + '.tmp', format='h264') # Start the overall timer start_time = datetime.now() # Set status start_record = True still_captured = False # Make sure timer is set motionStart = datetime.now() # Keep recording while there is still motion while pir.motion_detected: # If not first time around, put out a message if start_record: start_record = False else: print('Still recording for ' + str(settings.recordtime) + ' seconds') # Set the timer for this cycle start = datetime.now() # Keep recording for the specified time period while (datetime.now() - start).seconds < settings.recordtime: # Update the text on the clip every 0.2 seconds cam.annotate_text = settings.camTitle + " " + datetime.now( ).strftime('%d-%m-%y %H:%M:%S') cam.wait_recording(0.2) # If we are meant to be capturing a still, check to see if we need to do it now if ( datetime.now() - start_time ).seconds > settings.stillSeconds and not still_captured and settings.stillSeconds > 0: # The various stillMessage() in here are part of some debugging around auto-wide balance, because taking a still upsets it still_captured = True stillMessage(cam, '1') # Store the current AWB storeAWB = cam.awb_gains print(storeAWB) # Set the shutter speed to 1/100 cam.shutter_speed = 10000 stillMessage(cam, '2') # Take the picture on the Still Port cam.capture(recordStill, use_video_port=False) stillMessage(cam, '3') # Set the shutter speed back to auto cam.shutter_speed = 0 # Try to set the AWB back to what it was before cam.awb_mode = 'off' cam.awb_gains = storeAWB stillMessage(cam, '4') logMessage('Still captured') util.storeStill(recordStill, output_basefilename) # Capture the total recording time total_time = (datetime.now() - start_time).seconds # Stop recording cam.stop_recording() logMessage('Stopped recording after ' + str(total_time) + ' seconds') # Go to sleep to let everything settle time.sleep(5) # Rename file os.rename(recordVideo + '.tmp', recordVideo) # Store the video to NAS, update Plex and post to Slack util.storeVideo() return
""" Used to check motion sensors and the server's response. Using this we can send/receive feeds through adafruit IO whenever a motion is detected. """ # importing necessary libraries from Adafruit_IO import * from gpiozero import LED from gpiozero import MotionSensor # aio = Client(user_name, AIO key) aio = Client('moitbytes', 'aio_UJGo80Rfy67c3PJiX9At87u4UoYW') #setting up the client c = 0 # counter to count number of times led got on green_led = LED(17) # GPIO 17 pir = MotionSensor(4) # GPIO 4 green_led.off() while True: pir.wait_for_motion() # waiting for motion print("Motion Detected") green_led.on() c += 1 print(c) aio.send('led', c) # sending data to feed pir.wait_for_no_motion() # waiting for no motion green_led.off() print("Motion Stopped")
import RPi.GPIO as GPIO from gpiozero import MotionSensor #This sets the infrared sensor to be on the pin 5 irSense = MotionSensor(5) #This will then wait on this line untill motion is detected irSense.wait_for_motion()
#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()
def drive(lcd): try: f = init_fp(lcd) welcome_msg(lcd) lcd.lcd_display_string("Smart DL: Push Black", 2) lcd.lcd_display_string("QRCode: Push Red", 3) drive_enable = False while True: button_state_dl = GPIO.input(17) button_state_qr = GPIO.input(27) if button_state_dl == GPIO.HIGH: context, readers = init_smart_card_reader(lcd) state = init_smart_card(lcd, context, readers) lcd.lcd_display_string("Pls dont remove DL", 2) lcd.lcd_display_string('Place your finger..', 3) positionNumber, accuracyScore = verify_fp_from_sensor(lcd, f) welcome_msg(lcd) lcd.lcd_display_string("Pls dont remove DL", 2) lcd.lcd_display_string('FingerPrint Matched-1', 3) lcd.lcd_display_string('Verifying DL', 4) sleep(3) result = read_verify_dl(lcd, f, positionNumber) if (result == 0): welcome_msg(lcd) lcd.lcd_display_string("FP Matched-1", 2) lcd.lcd_display_string('DL check Fail', 3) lcd.lcd_display_string('Pls insert valid DL', 4) print("No match for DL") state = wait_new_smart_card(lcd, context, readers, state) #sleep(5) execfile("ssc3.py") else: print('Found template at position #' + str(positionNumber)) print('The accuracy score is: ' + str(accuracyScore)) drive_enable = True break elif button_state_qr == GPIO.HIGH: welcome_msg(lcd) lcd.lcd_display_string('Place your finger..', 2) positionNumber, accuracyScore = verify_fp_from_sensor(lcd, f) welcome_msg(lcd) lcd.lcd_display_string("FP - Matched", 2) sleep(2) #lcd.lcd_display_string("Show QR code", 2) #sleep(1) result = verify_qrcode(lcd) if (result == False): welcome_msg(lcd) lcd.lcd_display_string("QR Code Match Fail", 2) lcd.lcd_display_string("QR Code Attempts Over", 3) sleep(10) execfile(ssc3.py) else: print('QR code match') drive_enable = True break if drive_enable == True: welcome_msg(lcd) lcd.lcd_display_string("Wishing Safe Driving", 2) lcd.lcd_display_string("push red to stop", 3) sleep(1) motor.init() pir = MotionSensor(23) while True: motor.right(1) button_state_stop = GPIO.input(27) if button_state_stop == GPIO.HIGH: #motor.cleanup() welcome_msg(lcd) lcd.lcd_display_string("Car Stopped", 2) lcd.lcd_display_string("Motion: Push Red", 3) lcd.lcd_display_string("Exit: Push black", 4) break counter = 0 motion_detect = False while True: button_state_exit = GPIO.input(17) button_state_pir = GPIO.input(27) if button_state_exit == GPIO.HIGH: welcome_msg(lcd) lcd.lcd_display_string("Demo Over", 2) exit(1) elif button_state_pir == GPIO.HIGH or motion_detect: if motion_detect == False: welcome_msg(lcd) lcd.lcd_display_string("Motion Detect Started", 2) motion_detect = True try: with timeout(1, exception=RuntimeError): pir.wait_for_motion() counter = counter + 1 if counter > 2000: lcd.lcd_display_string("SMS sent", 3) gsm.sendsms( 'ALERT: Someone Locked in Car No: 1234') pass except RuntimeError: counter = 0 pass print("Motion detected!") #sleep(2) except Exception as e: GPIO.setmode(GPIO.BCM) print(e) #motor.cleanup() GPIO.cleanup() error_msg(lcd, e)
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()
from gpiozero import MotionSensor from gpiozero import LED import time pir1 = MotionSensor(17) pir2 = MotionSensor(27) buzz = LED(4) cnt1 = False cnt2 = False parked = 0 try: while True: cnt = pir1.motion_detected if cnt == True and parked == 0: print("Front wheel has been sensed by 1st") print("Waiting for front wheel to be sensed by 2nd") if pir2.wait_for_motion(2): print("front wheel sensed by 2nd") print("Wiating for back wheel to be sensed by 1st") time.sleep(2) if pir1.wait_for_motion(2): print("back wheel sensed by 1st") print("Car in") buzz.on() time.sleep(3) buzz.off() parked = 1 continue cnt2 = pir1.motion_detected if cnt2 == True and parked == 1: print("Back wheel going out by 1st sensor") print("Waiting for front wheel to be sensed by 2nd")