import RPi.GPIO as GPIO import time, os, threading GPIO_PIR = 23 GPIO_TRIGGER = 18 GPIO_ECHO = 24 THRESHOLD = 60 # cm TIMEOUT = 180 # sec ############################ GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(GPIO_PIR, GPIO.IN) GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) LAST_MOVE = 0 def distance(sample_size=5, sample_wait=0.01): # https://raw.githubusercontent.com/alaudet/hcsr04sensor/master/hcsr04sensor/sensor.py speed_of_sound = 331.3 sample = [] for distance_reading in range(sample_size): GPIO.output(GPIO_TRIGGER, GPIO.LOW) time.sleep(sample_wait) GPIO.output(GPIO_TRIGGER, True) time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) echo_status_counter = 1 sonar_signal_on, sonar_signal_off = time.time(), time.time() while GPIO.input(GPIO_ECHO) == 0: if echo_status_counter < 1000: sonar_signal_off = time.time() echo_status_counter += 1 #else: # raise SystemError('Echo pulse was not received') while GPIO.input(GPIO_ECHO) == 1: sonar_signal_on = time.time() time_passed = sonar_signal_on - sonar_signal_off distance_cm = time_passed * ((speed_of_sound * 100) / 2) sample.append(distance_cm) sorted_sample = sorted(sample) return sorted_sample[sample_size // 2] def standby(): d = distance() if d >= THRESHOLD: os.system("echo 1 > /sys/class/backlight/rpi_backlight/bl_power") # off else: os.system("echo 0 > /sys/class/backlight/rpi_backlight/bl_power") # on threading.Timer(TIMEOUT, standby).start() LAST_MOVE = time.time() def has_moved(channel): d = distance() if d <= THRESHOLD: os.system("echo 0 > /sys/class/backlight/rpi_backlight/bl_power") # on if time.time() - LAST_MOVE >= 1: threading.Timer(TIMEOUT, standby).start() try: #while True: GPIO.add_event_detect(GPIO_PIR , GPIO.RISING, callback=has_moved) while True: time.sleep(1) except KeyboardInterrupt: print "Beende..." GPIO.cleanup()