from gpiozero import MotionSensor
from time import sleep
from datetime import timedelta, datetime
from mbRequest import send

MOTION_SENSOR_PORT = 4
TIMEOUT = timedelta(minutes=5)
HAS_MOTION = False
last_visit = datetime.today()

msens = MotionSensor(MOTION_SENSOR_PORT)
#msens.when_motion() = motion()
#msens.when_no_motion() = no_motion()


def when_motion():
    last_visit = datetime.today()
    if not HAS_MOTION:
        HAS_MOTION = True
        send("Kontoret", True)


def when_no_motion():
    if last_visit + TIMEOUT < timedelta.today():
        HAS_MOTION = False
        send("Kontoret", False)
Beispiel #2
0
# importing camera interface, gpio interface, time, OpenCV2 image processing
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
from datetime import datetime
import cv2
import os
from gpiozero import LED, MotionSensor
import sys

# initializing the camera, gpio pins, and path to save photos
led = LED(17)
pir = MotionSensor(21)
camera = PiCamera()
rawCapture = PiRGBArray(camera)
#camera.resolution = (640, 480)
#camera.framerate = 32
#rawCapture = PiRGBArray(camera, size=(640, 480)))
now = datetime.now()
path = '/media/pi/TRAP_PIX/%02d%02d%04d_%02d_%02d_%02d' % (
    now.month, now.day, now.year, now.hour, now.minute, now.second)
if not os.path.exists(path):
    os.makedirs(path)

# allows camera time to boot
time.sleep(0.1)

picture_count = 0
photo_taken = False

while picture_count < 400:
def initializeMotionDetection():
    if motionDetectionEnabled:
        pir = MotionSensor(PIR_PIN)
        GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=motion_handler)
from gpiozero import MotionSensor
from picamera import PiCamera, Color
sense = MotionSensor(4)
mycamera = PiCamera()
from time import sleep
while True:
    sense.wait_for_motion()
    print("Motion detected!")
    mycamera.start_preview(fullscreen=False, window=(100, 200, 300, 400))
    sense.wait_for_no_motion()
    mycamera.stop_preview()
Beispiel #5
0
#!/usr/bin/python

# Importation des librairies pythons
from gpiozero import MotionSensor
from gpiozero import PWMLED
import random
import pygame

#GPIO utilise
GPIO_PIR = 4
GPIO_LED1 = 13
GPIO_LED2 = 19

pir = MotionSensor(GPIO_PIR)
ledG = PWMLED(GPIO_LED1)
ledD = PWMLED(GPIO_LED2)

ledG.value = 0
ledD.value = 0

pygame.init()


def playSound(_son, _repeat=0):
    pygame.mixer.init()
    pygame.mixer.music.load(_son)
    pygame.mixer.music.play(loops=_repeat)


def waitSound():
    while pygame.mixer.music.get_busy() == True:
Beispiel #6
0
def main():
    # from picamera import PiCamera
    from gpiozero import LED, Button, MotionSensor
    from gpiozero.tools import all_values, any_values
    from signal import pause
    # import logging
    import json
    import sys

    print('')
    print('# RPiMS is running #')
    print('')

    global redis_db
    redis_db = db_connect('localhost', 0)

    config_yaml = config_load('/var/www/html/conf/rpims.yaml')
    config = config_yaml['setup']
    zabbix_agent = config_yaml['zabbix_agent']
    gpio = config_yaml.get("gpio")
    sensors = config_yaml.get("sensors")
    bme280 = sensors['BME280']
    #print(bme280)
    #    for item in bme280:
    #        if (bme280[item]['interface'] == 'serial'):
    #            print(bme280[item])

    #    for item in bme280:
    #        if (bme280[item]['interface'] == 'i2c'):
    #            print(bme280[item])

    redis_db.flushdb()
    redis_db.set('gpio', json.dumps(gpio))
    redis_db.set('config', json.dumps(config))
    redis_db.set('zabbix_agent', json.dumps(zabbix_agent))

    get_hostip()
    hostnamectl_sh(**zabbix_agent)

    if bool(config['verbose']) is True:
        for k, v in config.items():
            print(f'{k} = {v}')
        for k, v in zabbix_agent.items():
            print(f'{k} = {v}')
        print('')

    if bool(config['use_door_sensor']) is True:
        global door_sensors_list
        door_sensors_list = {}
        for item in gpio:
            if (gpio[item]['type'] == 'DoorSensor'):
                door_sensors_list[item] = Button(gpio[item]['gpio_pin'],
                                                 hold_time=int(
                                                     gpio[item]['hold_time']))

    if bool(config['use_motion_sensor']) is True:
        global motion_sensors_list
        motion_sensors_list = {}
        for item in gpio:
            if (gpio[item]['type'] == 'MotionSensor'):
                motion_sensors_list[item] = MotionSensor(
                    gpio[item]['gpio_pin'])

    if bool(config['use_system_buttons']) is True:
        global system_buttons_list
        system_buttons_list = {}
        for item in gpio:
            if (gpio[item]['type'] == 'ShutdownButton'):
                system_buttons_list['shutdown_button'] = Button(
                    gpio[item]['gpio_pin'],
                    hold_time=int(gpio[item]['hold_time']))

    global led_indicators_list
    led_indicators_list = {}
    for item in gpio:
        if (gpio[item]['type'] == 'door_led'):
            led_indicators_list['door_led'] = LED(gpio[item]['gpio_pin'])
        if (gpio[item]['type'] == 'motion_led'):
            led_indicators_list['motion_led'] = LED(gpio[item]['gpio_pin'])
        if (gpio[item]['type'] == 'led'):
            led_indicators_list['led'] = LED(gpio[item]['gpio_pin'])

    if bool(config['use_door_sensor']) is True:
        for k, v in door_sensors_list.items():
            if v.value == 0:
                door_status_open(k, **config)
            else:
                door_status_close(k, **config)
        for k, v in door_sensors_list.items():
            v.when_held = lambda s=k: door_action_closed(s, **config)
            v.when_released = lambda s=k: door_action_opened(s, **config)
        if bool(config['use_door_led_indicator']) is True:
            led_indicators_list['door_led'].source = all_values(
                *door_sensors_list.values())

    if bool(config['use_motion_sensor']) is True:
        for k, v in motion_sensors_list.items():
            if v.value == 0:
                motion_sensor_when_no_motion(k, **config)
            else:
                motion_sensor_when_motion(k, **config)
        for k, v in motion_sensors_list.items():
            v.when_motion = lambda s=k: motion_sensor_when_motion(k, **config)
            v.when_no_motion = lambda s=k: motion_sensor_when_no_motion(
                k, **config)
        if bool(config['use_motion_led_indicator']) is True:
            led_indicators_list['motion_led'].source = any_values(
                *motion_sensors_list.values())

    if bool(config['use_system_buttons']) is True:
        system_buttons_list['shutdown_button'].when_held = shutdown

    if bool(config['use_CPU_sensor']) is True:
        threading_function(get_cputemp_data, **config)

    if bool(config['use_BME280_sensor']) is True:
        for item in bme280:
            bme280_config = bme280[item]
            threading_function(get_bme280_data, **bme280_config)

    if bool(config['use_DS18B20_sensor']) is True:
        threading_function(get_ds18b20_data, **config)

    if bool(config['use_DHT_sensor']) is True:
        threading_function(get_dht_data, **config)

    if bool(config['use_weather_station']) is True:
        threading_function(rainfall, **config)
        threading_function(wind_speed, **config)
        threading_function(wind_direction, **config)

    if bool(config['use_serial_display']) is True:
        threading_function(serial_displays, **config)

    if bool(config['use_picamera']) is True and bool(
            config['use_picamera_recording']) is False and bool(
                config['use_door_sensor']) is False and bool(
                    config['use_motion_sensor']) is False:
        av_stream('start')

    pause()
Beispiel #7
0
    if args.useWebsocket and args.certificatePath and args.privateKeyPath:
        parser.error(
            "X.509 cert authentication and WebSocket are mutual exclusive. Please pick one."
        )
        exit(2)

    if not args.useWebsocket and (not args.certificatePath
                                  or not args.privateKeyPath):
        parser.error("Missing credentials for authentication.")
        exit(2)

    # Configure logging
    logging.basicConfig(level=logging.INFO, format=piot.LOG_FORMAT)
    logger = logging.getLogger('pir_pub')
    logger.addHandler(watchtower.CloudWatchLogHandler(args.thing))

    # Init AWSIoTMQTTClient
    myAWSIoTMQTTClient = piot.init_aws_iot_mqtt_client(args)
    myAWSIoTMQTTClient.connect()

    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()
Beispiel #8
0
    # output pins set to 0
    GPIO.digitalWrite(27, GPIO.LOW)
    GPIO.digitalWrite(22, GPIO.LOW)
    # output pins set to input
    GPIO.pinMode(27, GPIO.INPUT)
    GPIO.pinMode(22, GPIO.INPUT)
    sys.exit("Good bye! :)")


# SETTING UP PINS
GPIO.wiringPiSetupGpio()
GPIO.pinMode(23, GPIO.INPUT)  # switching mode
GPIO.pinMode(24, GPIO.INPUT)  # capture picture from camera
GPIO.pinMode(25, GPIO.INPUT)  # exit from camera
GPIO.pinMode(18, GPIO.INPUT)  # motion detector input
pir = MotionSensor(18)  # motion detector input
GPIO.pinMode(27, GPIO.OUTPUT)  # LED indicates switching between modes
GPIO.pinMode(22, GPIO.OUTPUT)  # LED indicates taking a photo/video
GPIO.pullUpDnControl(23, GPIO.PUD_UP)
GPIO.pullUpDnControl(24, GPIO.PUD_UP)
GPIO.pullUpDnControl(25, GPIO.PUD_UP)

# HELLO MESSAGES
print("Photo mode\n")

# MAIN PROGRAM LOOP

MODE_FLAG = 0  # [0 - photo; 1 - video; 2 - motion detector

while True:
    if (GPIO.digitalRead(25) == GPIO.LOW):
          "storageBucket": "casa-90566.appspot.com",    
    #          "serviceAccount":  "base-rostros-firebase-adminsdk-2w8tl-1940b517ba.json"
          }
    try:
        firebase = pyrebase.initialize_app(config)
        db = firebase.database()
        # Para validara que si  se conecto se obtiene los datos de la los usuarios
        valores = db.child("Users").get()    
        entrenamiento = db.child("Facial/EntrenamientoHecho").get()    
    except:
        return False, firebase, db, valores,entrenamiento
    return conexionExitosa, firebase, db, valores, entrenamiento.val()

from gpiozero import MotionSensor, LED
ledes = LED(17)
pir = MotionSensor(4) # Numero de pin de raspberry

conexionExitosa, firebase, db, valores, entrenamiento = conectarFirebase()
if conexionExitosa:
    print("SE conecnto con firebase")
    while True:
        deteccionPasillo = db.child("Habitaciones/Pasillo2/Presencia").get()
        deteccionPasillo = deteccionPasillo.val()
        puertaAbierta = db.child("Habitaciones/Entrada/Puerta").get()
        puertaAbierta = puertaAbierta.val()
        if puertaAbierta == "Encender":
            if pir.motion_detected == False and deteccionPasillo== False :
                print("Se va a cerrar la PUERTA")
                db.child("Habitaciones/Entrada").update({"Puerta":"Apagar"})
                time.sleep(10)        
        
Beispiel #10
0
from time import sleep, time
import board
import digitalio
import busio
import adafruit_bmp280
import pandas as pd

i2c = busio.I2C(board.SCL, board.SDA)
bmp280 = adafruit_bmp280.Adafruit_BMP280_I2c(i2c)
bmp280.seaLevelhPa = 1013.25

print('(debug sesh)temp: {0:0.1f}'.format(bmp280.temperature))

vacum = LED(19)
magnet = LED(17) #config magnet pin
infra = MotionSensor(13) #use queue_len if it detects twitchy

def main():
    print('Experiment is starting...')
    magnet.on()
    print('Magnet on.')
    inp = input('Please enter s to start.')
    if(inp == 's'):
        print('Magnet off. Ball is releasing.')
        magnet.off()
        start = time()
        while(not infra.motion_detected()):
            end = time()
        time = end - start
        height = 100 #adjust height probably not correct
        print('Time is: {0:0.3f} \n Time^2 is: {1:0.3f} \n'.format(time,time**2))
Beispiel #11
0
"""
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")
Beispiel #12
0
#!/usr/bin/env python
# Title: Simple motion prober software
# Caution:
# 1. Check location of  + DC voltage and GND line
# 2. Change sensor and pulse button (orange color) appropriately
#


# PIR Motion Sensor:                ,--------.
# . Power (+DC voltage):  2,2 ------|        |
# . Signal(Output)     : 11,7 ------| PIR    | GPIO17 = pin no. 11
# . GND (Ground)       :  6,6 ------| Sensor |
#                                   `--------'

from gpiozero import MotionSensor
import time

print "Starting motion sensor..."
pir = MotionSensor(17) # GPIO17 = pin no. 11
count = 0
while True:
        pir.wait_for_motion()
        count += 1
        print ("Motion Detected! " + str(count))
        time.sleep(1)
print "GPIO.cleanup()"
GPIO.cleanup()


from dotenv import load_dotenv
load_dotenv()

# chose HTTP, AMQP or MQTT as transport protocol
PROTOCOL = IoTHubTransportProvider.AMQP
CONNECTION_STRING = os.getenv('iot_connection_string')
MSG_TXT = \
    "{\"datetime\": \"%s\", " \
    "\"online\": %i, \"total\": %i}"
MESSAGE_COUNTER = 0
SEND_REPORTED_STATE_CALLBACKS = 0
SEND_CALLBACKS = 0
RECEIVE_CALLBACKS = 0

# GPIO - change these to match your GPIO
motion_sensor = MotionSensor(4)
led = LED(2)
buzzer = Buzzer(17)


def send_confirmation_callback(message, result, user_context):
    global SEND_CALLBACKS
    print("Confirmation[%d] received for message with result = %s" %
          (user_context, result))
    map_properties = message.properties()
    key_value_pair = map_properties.get_internals()
    print("\tProperties: %s" % key_value_pair)
    SEND_CALLBACKS += 1
    print("\tTotal calls confirmed: %d" % SEND_CALLBACKS)

#
def blink(LED, secs_between_blinks, num_blinks):
    count = 0
    while count < num_blinks * 2:
        LED.toggle()
        time.sleep(secs_between_blinks / 2)
        count += 1
    return


# initializing the gpio pins
ir_illuminator = LED(14, active_high=False)
ir_illuminator.off()
LED_indicator = LED(4)
LED_indicator.off()
passive_infrared = MotionSensor(27)
button = Button(17, hold_time=3)

# initializing the camera
camera = PiCamera()
rawCapture = PiRGBArray(camera)

# initializing unique paths and names to save photos
now = datetime.now()
#path = '/home/pi/Desktop/%02d%02d%04d_%02d_%02d_%02d' % (now.month, now.day, now.year, now.hour, now.minute, now.second)
folder_path = '/media/pi/TRAP_PIX/%02d%02d%04d_%02d_%02d_%02d' % (
    now.month, now.day, now.year, now.hour, now.minute, now.second)
while not os.path.ismount('/media/pi/TRAP_PIX'):
    print("can't find")
    time.sleep(2)
else:
Beispiel #15
0
from gpiozero import MCP3008
from gpiozero import Buzzer
from gpiozero import MotionSensor
from time import time
from time import sleep

from twilio.rest import Client

pir = MotionSensor(26, sample_rate=5, queue_len=1)
bz = Buzzer(5)

account_sid = "AC2c93ac93d1b535cb4cc943bbda8fbed7"
auth_token = "eeaa2ed6768129d4ca22c355fc1693ed"
client = Client(account_sid, auth_token)

my_hp = "+6596651442"
twilio_hp = "+15702410802"

adc = MCP3008(channel=0)

while True:
    bz.off()
    old_time = time()
    pir.wait_for_motion()
    new_time = time()
    if new_time - old_time > 1:
        print("Motion detected after {:.2f} seconds".format(new_time -
                                                            old_time))
        bz.on()
        sleep(1)
        bz.off()
Beispiel #16
0
logfile = logdir + '/trailcam_log-' + str(
    datetime.now().strftime('%Y%m%d-%H%M')) + '.csv'
logging.basicConfig(filename=logfile,
                    level=logging.DEBUG,
                    format='%(asctime)s %(message)s',
                    datefmt='%Y-%m-%d, %H:%M:%S,')

serial = i2c(port=1, address=0x3C)
display = ssd1306(serial)
UP_BUTTON = Button(13)
DOWN_BUTTON = Button(26)
LEFT_BUTTON = Button(6)
RIGHT_BUTTON = Button(0)
ACTION_BUTTON = Button(5)
HOME_BUTTON = Button(19)
PIR = MotionSensor(23)
# Camera Mode High => Day Mode, Low => Night Mode
CAMERA_CONTROL = DigitalOutputDevice(21, True, True)

# Work out height of text
text_height = 0
with canvas(display) as draw:
    w, text_height = draw.textsize(" ")

# prev icon (small)
# gap
# icon (large)
# gap
# text
# gap
# next icon (small)
 def __init__(self):
     self.pir = MotionSensor(4)
     self.motion_detected = self.pir.motion_detected
Beispiel #18
0
from gpiozero import MotionSensor, LED
from subprocess import call
from picamera import PiCamera
from datetime import datetime
from signal import pause
import smtplib

## Working!!  Will repeatedly send emails on motion

# create smtp session
#s = smtplib.SMTP('smtp.gmail.com', 587)

# Set pin for motion sensor
# pir = MotionSensor(4) # as in pin 7
pir = MotionSensor(27)  # as in pin 7
camera = PiCamera()
camera.rotation = 180  # for upside down camera
camera.resolution = (1250, 950)  ## setting from internet
camera.framerate = 90

pwd = open("notMuch.dat", "r")
pwd2 = pwd.read()


# Define camera action
def takePic():
    ## Photo business
    tstamp = datetime.now().isoformat()
    camera.capture(
        '/home/joelpione/Adeept-RPi-Kit-to-gpiozero/testPics/%s.jpg' % tstamp)
    ## Play wav
Beispiel #19
0
import time

from gpiozero import MotionSensor

motion_counter = 0

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

cred = credentials.Certificate("credentials.json")
firebase_admin.initialize_app(cred)

db = firestore.client()

pir = MotionSensor(23)  #PIR motion sensor is connected to Pin23
print("Waiting for PIR to settle")
pir.wait_for_no_motion(
)  #When first powered on, the PIR motion sensor will trigger itself for several time, which is normal,
#thus, we can call a wait_for_no_motion(), then only let the program continue to runs.


def connect():
    global motion_counter
    while True:
        pir.wait_for_motion()
        if (pir.wait_for_motion()):
            motion_counter += 1
            if motion_counter >= 3:  #only store data if the motion has been triggered more than 3 times.
                print("Motion detected!", str(datetime.now()))
Beispiel #20
0
from datetime import datetime
from gpiozero import Buzzer, LED, MotionSensor
from signal import pause
from text_me import texter
buzzer = Buzzer(4)
led = LED(14)

motion_sensor = MotionSensor(18)


def start_motion():
    detection = datetime.now()
    led.blink(0.5, 0.5)
    buzzer.beep(0.5, 0.5)
    print(f"Motion detected at {detection}")
    texter(detection)


def end_motion():
    led.off()
    buzzer.off()


print("Starting up the sensor...")
motion_sensor.wait_for_no_motion()
print("Sensor ready")
motion_sensor.when_motion = start_motion
motion_sensor.when_no_motion = end_motion

pause()
Beispiel #21
0
		if valid:
			publish()
		
def motion_detected():
	global mqttClient, motion_topic
	
	timestamp = time.time()
	data = {
		'Timestamp': timestamp
	}
	
	mqttClient.publish(motion_topic,json.dumps(data),1)

mqttClient = getMQTTClient()
mqttClient.subscribe('{}/controls/#'.format(topic), 1, mqttCallback)
		
dht11_monitor = DHT11_Monitor(dht11_pin)
ldr_monitor = LDR_Monitor(ldr_channel)
mqtthandler = MQTT_Handler()

dht11_monitor.start()
ldr_monitor.start()
mqtthandler.start()

pir = MotionSensor(motionsensor_pin)
pir.when_motion = motion_detected

try:
	pause()
except KeyboardInterrupt:
	os._exit(0)
Beispiel #22
0
 def __init__(self):
     self.sensor = MotionSensor(self.PIN)
     self.last_motion = datetime.now()
     Thread(target=self.record_motion).start()
Beispiel #23
0
########## Porject for one direction OUT ####
## THE PROJECT RUN IN THE SECQUENCE
## 1-eihOUT.py
## 2- subprocessApp2.py
## 3- detect.py -> send data to post_data_to_api.py
import time
from gpiozero import MotionSensor
from gpiozero import LED
import subprocess
import signal
import os
## LED Temporory TO BE DELETED AFTER
red_led = LED(17)
red_led.off()
## PIR Sensors Conections
pir = MotionSensor(4)
pir2 = MotionSensor(24)

## run the project for ever.
while True:
    print('PIR ONE DETECTING ....')
    if(pir.wait_for_motion()):
        print("> PIR ONE ON < ")
        ## once the First sensor is ON
        ## another process will run to check sensor two
        p = subprocess.run(["python /home/pi/year4/projectEIH/body-detect/subprocessApp2.py"], shell=True)
        ##### HERE I NEED THE HELP: NOW THE PROCESS RUN IN THE BACKGROUBD AND ANOTHER PROCESS READY TO GO
        ##### LIKE: p2 = ... IS WAITING WHILE p .. IS WORKING
        pir.wait_for_no_motion()
        print("STORED")
Beispiel #24
0
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 back wheel to be sensed by 1nd")
            time.sleep(2)
            if pir1.wait_for_motion(2):
                print("back wheel sensed by 1st ")
                print("Waiting for the front tip to be sensed by 2nd")
                if pir2.wait_for_motion(2):
                    print("tip sensed by 2nd")
                    print("Car in")
                    buzz.on()
                    time.sleep(3)
                    buzz.off()
                    parked = 1
                    continue
        cnt2 = pir2.motion_detected
        if cnt2 == True and parked == 1:
            print("Tip sensed moving back by 2nd")
            print("Waiting for back wheel to be sensed 1st")
Beispiel #25
0
# importing important libraries
from gpiozero import MotionSensor
import picamera
from datetime import datetime
from time import sleep

# setting sensor to recive output over GPIO port 4
pir = MotionSensor(4)

# setup the loop
while True:
    # giving file path and setting rules to name a file with current time and also with format given in line 17
    filepath = "/home/pi/Desktop/Codes/SmartCam"
    currentTime = datetime.now()
    time = currentTime.strftime("%Y.%m.%d-%H%M%S")
    name = time + '.h264'
    CompletePath = filepath + name
    print('Waiting for motion.')
    # setting camera object
    with picamera.PiCamera() as camera:
        camera.resolution = (1280, 720)
        pir.wait_for_motion
        #if else to wait for motion, where sleep is the time it need to take in order to stop recording
        if pir.motion_detected:
            camera.start_recording(name)
            pir.wait_for_no_motion
            sleep(5)
            camera.stop_recording()
            print('recording ..... Done')
# this will print message if no motion occur and program wait for motion to occur
        print('No motion at the moment')
Beispiel #26
0
#use DHT22 sensor: yes/no
use_DHT22_sensor = "no"

#use DS18B20 sensor: yes/no
use_DS18B20_sensor = "no"

# Led Lamp or Relay
led = LED(18)

#Button type sensors inputs: Door/Window, Smoke Alarm, CO Alarm, CO2 Alarm, Heat Alarm, Water Alarm sensors inputs (store the ref of functions in variable)

door_sensor_1 = Button(22, hold_time=3)
door_sensor_2 = Button(23, hold_time=3)

#Motion Sensor inputs on GPIO 12:
MotionSensor_1 = MotionSensor(12)

#Waveshare LCD/OLED
button1 = Button(21)
button2 = Button(20)
button3 = Button(16)
joystick_left = Button(5)
joystick_up = Button(6)
joystick_fire = Button(13, hold_time=5)
joystick_down = Button(19)
joystick_right = Button(26)

button_sensor_list = {
    "button_1": button1,
    "button_2": button2,
    "button_3": button3,
Beispiel #27
0
import time

import RPi.GPIO as GPIO
from gpiozero import MotionSensor

import Flask.alarmservice as AlarmService

# Variables
MAIN_PATH = "/home/pi/PiSec"

# PIN
red_PIN = 16
pir = MotionSensor(17)
buzz_PIN = 26
green_PIN = 27

already_took = False


def check_motion():
    global already_took
    if pir.motion_detected and not already_took:
        print("Motion detected!")
        print("Taking picture!")
        AlarmService.take_picture_auto()
        already_took = True
        print("Done!")
        beep()
        beep()
        beep()
    else:
Beispiel #28
0
from gpiozero import MotionSensor, LED, Button
from signal import pause
from time import sleep

## A little laggy, but button hold activates, then motion does set routing


myLed = LED(17) # pin 11 / GPIO17
pir = MotionSensor(27) # pin 13 GPIO27 (wonky zero GPIO02).. test on Pi3, works 0
# pir = MotionSensor(4) # as in pin 7, GPIO4.. works on Pi 3

## Button setup
button = Button(16) ## PiZero.. grr Pin 38 GPIO16, 3rd from end outside
# button = Button(20) # Pi3 standard map, GPIO20, pin 38
button.hold_time = 4 # secs?

## Action setting for single button press, i.e, busily do nothing
def btnPressFun():
    myLed.blink(.1)
    print("do nothing")
    pir.when_motion = noPicsFun

## Action sequence for after button held.
def btnHoldFun():
    myLed.blink(3)
    print("Run camera")
    sleep(12)
    myLed.off()
    pir.when_motion = cameraEmailFun

## This will be the big function to do everything    
Beispiel #29
0
 def __init__(self):
     self.last_msg_sent_at = 0
     self.pir = MotionSensor(14)
#!/usr/bin/env python3
# Title: Simple motion prober software
# Caution:
# 1. Check location of  + DC voltage and GND line
# 2. Change sensor and pulse button (orange color) appropriately
#

# PIR Motion Sensor:                ,--------.
# . Power (+DC voltage):  2,2 ------|        |
# . Signal(Output)     : 11,7 ------| PIR    | GPIO17 = pin no. 11
# . GND (Ground)       :  6,6 ------| Sensor | GPIO4  = pin no. 7
#                                   `--------'

from gpiozero import MotionSensor
import time

print("Starting motion sensor...")
pir = MotionSensor(4)  # GPIO4 = pin no. 7
count = 0
while True:
    pir.wait_for_motion()
    count += 1
    print("Motion Detected! " + str(count))
    # pir.wait_for_no_motion()
    # print ("Motion Stopped! ")
    time.sleep(1)
print("GPIO.cleanup()")
GPIO.cleanup()