Would you be able to assist a noobie here with a small python script?
Editing my question. As the below code worked for what it was intended.
Now what i am trying to achieve is that i also have a second script. (posted below) That controls a PIR Sensor wich ALSO turns the light on. But i would like to try and merge the two scripts into 1 single script.
It should as default use the PIR sensor to turn the light on when movement is detected. But! If the button is pushed it should override the sensor and leave the light on for 15 minutes.
As i have it set up now the pir does its job. But if there is no movement in front of it and i push the button it turns the light on then quickly off again as the pir is detecting no movement..
Both scripts below. All help i can get is very very much appreciated. :)
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(4, GPIO.IN) #Read output from PIR motion sensor
while True:
i=GPIO.input(4)
if i==0: #When output from motion sensor is LOW
print "No movement detected - Turning lights off",i
exec(open("./LightsOff.py").read(), globals())
time.sleep(0.1)
elif i==1: #When output from motion sensor is HIGH
print "Movement detected - Turning lights on",i
exec(open("./LightsOn.py").read(), globals())
time.sleep(60 * 15)
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
input_state = GPIO.input(18)
if input_state == False:
print('Button Pressed')
execfile("LightsOn.py")
time.sleep(0.2)
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
starttime = 0
while True:
if GPIO.input(18) == False and starttime == 0:
#waiting for release button
while not GPIO.input(18):
pass
starttime = time.time()
print('Turning on Kitchen Lights for 15 minutes')
exec(open('LightsOn.py').read())
if (time.time() - starttime) < (15*60) and starttime != 0 and GPIO.input(18) == False:
#waiting for release button
while not GPIO.input(18):
pass
exec(open('LightsOff.py').read())
starttime=0
if (time.time() - starttime) > (15*60) and starttime != 0:
exec(open('LightsOff.py').read())
starttime=0
You can use time.time() function for timings.
Also you can use time.sleep(0.1) at the end of the while loop for decreasing cpu load
Script should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.