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 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()
motion_sensor_status = True lcd.clear() lcd.color = [0, 0, 100] lcd.message = 'Alarm is on' #motion detected response def motion_detected(): global motion_sensor_status if (motion_sensor_status == True): if (pir.motion_detected): lcd.clear() lcd.color = [100, 0, 0] lcd.message = 'Alarm is on\nMotion detected!' led.blink() buzzer.blink() else: lcd.clear() lcd.color = [0, 0, 100] lcd.message = 'Alarm is on' led.off() buzzer.off() button.when_pressed = arm_motion_sensor pir.when_motion = motion_detected pir.when_no_motion = motion_detected #keep running to continuously check the pushbutton and pir states 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()
from gpiozero import MotionSensor, LED pir = MotionSensor(26) led = LED(17) pir.when_motion = led.on pir.when_no_motion = led.off
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 from signal import pause vib = MotionSensor(4) led = LED(16) vib.when_motion = print("Motion Detected") vib.when_no_motion = print("No Motion") pause()
from gpiozero import MotionSensor from signal import pause import datetime print("Connecting ...") pir = MotionSensor(24) print("Connected") def sleep(): message("Zzzzz...") def alert(): message("ALERT") def message(text): date = datetime.datetime.now() print '%02d:%02d:%02d' % (date.hour, date.minute, date.second) + " " + text pir.when_motion = alert pir.when_no_motion = sleep pause()
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()
def action_pressed(): BaseState.current_state.action() def home_pressed(): BaseState.current_state.home() def motion_detected(): BaseState.current_state.motion_detected() def motion_stopped(): BaseState.current_state.motion_stopped() UP_BUTTON.when_pressed = up_pressed DOWN_BUTTON.when_pressed = down_pressed LEFT_BUTTON.when_pressed = left_pressed RIGHT_BUTTON.when_pressed = right_pressed ACTION_BUTTON.when_pressed = action_pressed HOME_BUTTON.when_pressed = home_pressed PIR.when_motion = motion_detected PIR.when_no_motion = motion_stopped BaseState.pir = PIR while BaseState.current_state.is_running(): if BaseState.current_state.should_update(): BaseState.current_state.show(display)
from gpiozero import MotionSensor, Buzzer, LED from signal import pause pir = MotionSensor(18) led = LED(16) buzzer = Buzzer(21) def on(self): led.on() buzzer.on() def off(self): led.off() buzzer.off() pir.when_motion = on pir.when_no_motion = off pause()
time.sleep(ON_CYCLE) # define ScreenOff routine for callback def screen_off(): s_pir = mMotionSensor.value if DEBUG: print("Screen off", s_pir) call(["/usr/bin/vcgencmd", "display_power", "0"], stdout=open(os.devnull, 'wb')) time.sleep(REFRESH_CYCLE) # Setup callbacks mMotionSensor.when_motion = screen_on mMotionSensor.when_no_motion = screen_off # Wait for MagicMirror Boot # approx. 13min for a RaspberryPi Zero W print("Waiting for MagicMirror boot to finish...") time.sleep(BOOT_TIME / 2) print("Waiting for MagicMirror boot to finish (2/2) ...") time.sleep(BOOT_TIME / 2) # Set initial state print("Fetching initial state...") if mMotionSensor.value == 0: call(["/usr/bin/vcgencmd", "display_power", "0"], stdout=open(os.devnull, 'wb')) else: call(["/usr/bin/vcgencmd", "display_power", "1"],
buzzer.off() sleep(0.2) if stopped: red.off() blue.off() buzzer.off() stopped = False def on_idle(): print("On idle called") global triggered if triggered: print("Stopping the alarm") global stopped stopped = True red.off() blue.off() buzzer.off() pir.when_no_motion = on_idle pir.when_motion = on_motion print("Alarm is set") input("Press any key to exit...") except KeyboardInterrupt: print("Quiting...") red.off() blue.off() buzzer.off()
async def displaySnowflake(): oled.drawSnowflake() # keep the value on the screen for a set amount of time await asyncio.sleep(OLED_SCREEN_TIMEOUT) oled.clearScreen() async def displayUmbrella(): oled.drawUmbrella() # keep the value on the screen for a set amount of time await asyncio.sleep(OLED_SCREEN_TIMEOUT) oled.clearScreen() # handlers pir.when_motion = onMotion pir.when_no_motion = onMotionStop keyRackSwitch.when_pressed = keyRackSwitchDisengaged keyRackSwitch.when_released = keyRackSwitchEngaged try: oled.clearScreen() pixels.animateOff() pause() except (KeyboardInterrupt, SystemExit) as exErr: print("Closing down application") finally: oled.clearScreen() pass
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()
#!/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()
def on_button_press(): """ Takes a photo when the button is pressed """ lights.red.off() lights.green.on() vrint("Photo captured.") camera.capture(timestamp_format(datetime.now(), filename=True)) lights.green.off() lights.red.on() if __name__ == "__main__": button = Button(17) sensor = MotionSensor(15) lights = TrafficLights(2, 3, 4) camera = PiCamera() lights.red.off() lights.amber.off() lights.green.off() verbose = True auth_tokens = load_auth_tokens('twitter_auth.json') auth = tweepy.OAuthHandler(auth_tokens['consumer_key'], auth_tokens['consumer_secret']) auth.set_access_token(auth_tokens['access_token'], auth_tokens['access_token_secret']) api = tweepy.API(auth) lights.red.on() sensor.when_motion = on_motion sensor.when_no_motion = on_no_motion button.when_pressed = on_button_press pause()
return def timer_recorrente(): print("Repetição") global timer timer = Timer(8.0, led[1].off) timer.start() return def parar_timer(): global timer if timer != None: timer.cancel() timer = None return def applet_evento(): dados = {"value1": (sensor_light.value*100), "value2": (sensor_distance.distance*100)} resultado = post(endereco, json=dados) print(resultado.text) return sensor.when_motion = detecta_movimento sensor.when_no_motion = detecta_inercia botao.when_pressed = applet_evento # criação de componentes # loop infinito
def notify_motion(): notify("Hareket Algilandi") def notify_no_motion(): notify("Hareketli Durdu") def notify(msg): for chat_id, listening in chat_listen.items(): # if chat_listen_switch: if listening: bot.sendMessage(chat_id, msg) #Get the photo camera = picamera.PiCamera() camera.capture('capture.jpg') camera.close() bot.sendPhoto(chat_id, photo=open('capture.jpg', 'rb')) pir.when_motion = notify_motion pir.when_no_motion = notify_no_motion bot = telepot.Bot('292346928:AAFkTCWYOBW7Xq19Utg8pCgs2fBXIRfKdcg') bot.message_loop(handle) print 'Uygulama Calisti' while True: time.sleep(10)
'Bucket': 'alexa-admin-2007563204634-env', 'Name': key } }, TargetImage={ 'S3Object': { 'Bucket': 'fyp-caller-images', 'Name': target_file } }) for faceMatch in response['FaceMatches']: position = faceMatch['Face']['BoundingBox'] similarity = str(faceMatch['Similarity']) global nameMatch nameMatch = key print(nameMatch + " The face at " + str(position['Left']) + " " + str(position['Top']) + " matches with " + similarity + "% confidence") if len(response['FaceMatches']) == 1: j = j + 1 return j return response['FaceMatches'] # When motion detected begin 'take_photo' method pir.when_motion = take_photo # When no motion detected run the 'stop_camera' method pir.when_no_motion = stop_camera pause()
import logging logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.INFO) logging.info("Initializing devices...") northeast_lamp = LED(2, active_high=False) southeast_lamp = LED(3, active_high=False) northeast_sensor = MotionSensor(14) southeast_sensor = MotionSensor(15) logging.info("Setting up device handlers...") northeast_sensor.when_motion = partial(logging.info, "northeast sensor has activated") northeast_sensor.when_no_motion = partial(logging.info, "northeast sensor has deactivated") southeast_sensor.when_motion = partial(logging.info, "southeast sensor has activated") southeast_sensor.when_no_motion = partial(logging.info, "southeast sensor has deactivated") logging.info("Setting up scheduled handlers...") always( at_dawn, do(partial(logging.info, "DAWN"), turn_lamp_off(northeast_lamp), turn_lamp_off(southeast_lamp))) always( at_dusk, do(partial(logging.info, "DUSK"), turn_lamp_on(northeast_lamp),
from gpiozero import MotionSensor from signal import pause motion_sensor = MotionSensor(4) def motion(): print("The movement found") def no_motion(): print("No movement found !") print("Readying the Sensor") motion_sensor.wait_for_no_motion() print("Sensor Ready") motion_sensor.when_motion = motion motion_sensor.when_no_motion = no_motion pause()
from gpiozero import MotionSensor, LED from signal import pause pir = MotionSensor(14) def print_motion(): print("motion") def print_no_motion(): print("no_motion") pir.when_motion = print_motion pir.when_no_motion = print_no_motion pause()
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() entrTopSensor.when_motion = None exitTopSensor.when_motion = None
def motion_not_detected_handler(): video_off() def motion_detection_handler(): print("motion detected") video_on(120) def switch_hold_handler(): print("switch off, exiting") onLED.off() exit() if __name__ == "__main__": print("starting") infredLEDs = LED(5) onLED = LED(24) onLED.on() switch = Button(10) switch.when_held = switch_hold_handler camera = PiCamera() camera.resolution = (1920, 1080) pir = MotionSensor(25) pir.when_motion = motion_detection_handler pir.when_no_motion = motion_not_detected_handler 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()
stream.truncate() # 기존 내용을 버리는 작업 if not motion.value: writer.write(struct.pack('<L', 0)) # 스트리밍 끝 writer.flush() break def start_record(): led.on() now = datetime.datetime.now() fname = now.strftime("%T%m%d_%H%M") + ".h264" camera.start_recording(fname) threading.Thread(target=video_streaming).start() def stop_record(): led.off() camera.stop_recording() motion.when_motion = start_record motion.when_no_motion = stop_record pause() # 응용 # PIR 대신 초음파 센서운영 # 물체가 일정 거리 안으로 진입시 운영 # 물체가 차량인 경우 # 이미지에서 차량의 번호판 영역 추룰(OpenCV로 가능 - 인터넷에 소스 많음) # AI를 이용하여 번호판 번호 해석 # 차량 번호에 따라 출입 통제 등
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()
agora = datetime.now() hora = agora.strftime("%H:%M:%S") endereco_foto = "./fotos/foto-" + hora + ".jpeg" foto = "fswebcam " + endereco_foto #print(foto) system(foto) print("tirei foto") global timer timer = Timer(3.0, tirar_foto) timer.start() def movimento_detectado(): print("mov") global timer timer = Timer(3.0, tirar_foto) timer.start() def movimento_inerte(): print("iner") global timer if (timer != None): timer.cancel() sensor_de_movimento.when_motion = movimento_detectado sensor_de_movimento.when_no_motion = movimento_inerte app.run(port=5000, debug=False)
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
from gpiozero import MotionSensor from signal import pause pir = MotionSensor(21) pir.when_no_motion() print('no motion') pir.when_motion() print('motion') pause()
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 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()