而条件不符合python

时间:2013-11-16 14:02:22

标签: python loops raspberry-pi gpio

好吧,我正在尝试开发一个家庭闹钟,根据从PIR模块收到的反馈(使用树莓派及其GPIO)拍摄照片。

问题如下。当PIr被触发时,需要5个图片,然后转到一个函数,该函数在接下来的5秒内仍然会检查另一个触发器,或者再次触发它。

只有在5秒钟过去的情况下(time.time()< start + secs)并且没有检测到任何移动(Curren_State仍然== 0)

我遇到问题的代码块:

#secs is received as a parameter (let's say the integer 5)

while time.time() < start + secs or not Current_State==True:
    Current_State = GPIO.input(GPIO_PIR)
    if Current_State==1:
        takePics(3)

问题:当我犯这种情况时(没有OR):

while time.time() < start + secs:
     #CODE

脚本似乎正常:如果5秒钟过去就会消失。但是如果我添加的条件(*或者不是Current_State == True *)它只是没有参加第一个条件,因为我在每个循环中显示 time.time()和<的比较em> start + secs 我看到第一个比第二个大,并且仍在执行while。

所以我仍在开发代码,但代码或多或少是这样的。如果以下代码没有很好地总结:http://pastebin.com/0xP4Le1U

# Import required Python libraries

# Here I define GPIO stuff

# Photo dimensions and rotation

# global variables
Current_State=0
Previous_State=0


def takePics(nPics):
    #Here I take pics

def reCheck:
    global Current_State, alert

    alert=0
    start = time.time()
    Current_State = 0

    while time.time() < start + secs or not Current_State==True:
        Current_State = GPIO.input(GPIO_PIR)
        if Current_State==1:
            takePics(3)

            #If there's no movement, this alert remains =0 
            #and will exit the "while" from which it was called 
            alert=1

#Here I have more functions like sendEmail and so on

def main():
    #main code

    while True:

         #SOME CODE

         if Current_State==1 and Previous_State==0:
            print "----> Motion detected!"

            Previous_State = 1
            alert=1

            #sendMail()
            switchLightON() # Switch on the light using the relay
            takePics(5)

            while alert==1:
                reCheck(4) # we check again in case movement was detected in reCheck

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:3)

or更改为and。或者,如果not Current_State==True是布尔值,请考虑将Current_State is not True简化为not Current_State或仅Current_State

while time.time() < start + secs and Current_State is not True:
    Current_State = GPIO.input(GPIO_PIR)
    if Current_State==1:
        takePics(3)

这将循环,直到secs秒已经过去,或者Current_State停止为真。诀窍是,只有在条件 false 时停止。仅当两个条件均为假时or为false,如果 条件为false,则and为false。