将两个Python的while循环合并为一个

0 投票
1 回答
3141 浏览
提问于 2025-04-18 06:57

我需要把我的Python代码合并在一起,当门关上时,PIR传感器会开始检测运动。但是当我把这两个文件合并时,它只运行了第一个循环,没能继续到下一个循环。有人能帮我解决这个问题吗?

第一个循环:

#function for door closing
def door_open():
    print("Door Open")

# function for the door closing
def door_close():
    print("Door Close")

while True:
    if GPIO.input(door_sensor): # if door is opened
        if (sensorTrigger):
           door_open() # fire GA code
           sensorTrigger = False # make sure it doesn't fire again
        if not io.input(door_sensor): # if door is closed
            if not (sensorTrigger):
                door_close() # fire GA code
                sensorTrigger = True # make sure it doesn't fire again

第二个循环:

Current_State  = 0
Previous_State = 0


# Loop until PIR output is 0
while GPIO.input(GPIO_PIR)==1:
   Current_State  = 0

print "  Ready"

while True :

  # Read PIR state
  Current_State = GPIO.input(GPIO_PIR)

  if Current_State==1 and Previous_State==0:
    # PIR is triggered
    print "  Motion detected!"
    # Record previous state
    Previous_State=1
  elif Current_State==0 and Previous_State==1:
    # PIR has returned to ready state
    print "  Ready"
    Previous_State=0

# Wait for 10 milliseconds
time.sleep(0.01)

except KeyboardInterrupt:
  print "  Quit"
  # Reset GPIO settings
  GPIO.cleanup()

我尝试把这两个循环合并在一起,但结果只有第一个循环在运行。

#function for door closing
def door_open():
    print("Door Open")

# function for the door closing
def door_close():
    print("Door Close")

while True:
    if GPIO.input(door_sensor): # if door is opened
        if (sensorTrigger):
           door_open() # fire GA code
           sensorTrigger = False # make sure it doesn't fire again
        if not io.input(door_sensor): # if door is closed
            if not (sensorTrigger):
                door_close() # fire GA code
                sensorTrigger = True # make sure it doesn't fire again

door_close_thread = threading.Thread(target=door_close)
door_close_thread.daemon =  True
door_close_thread.start()

Current_State  = 0
Previous_State = 0

try:
  print "Waiting for PIR to settle..."

  # Loop until PIR output is 0
  while GPIO.input(GPIO_PIR)==1:
    Current_State  = 0

  print "  Ready"

  while True :

    # Read PIR state
    Current_State = GPIO.input(GPIO_PIR)

    if Current_State==1 and Previous_State==0:
      # PIR is triggered
      print "  Motion detected!"
      # Record previous state
      Previous_State=1
    if not Current_State==0 and Previous_State==1:
      # PIR has returned to ready state
      print "  Ready"
      Previous_State=0

# Wait for 10 milliseconds
time.sleep(0.01)

except KeyboardInterrupt:
  print "  Quit"
  # Reset GPIO settings
  GPIO.cleanup()

1 个回答

0

不要使用两个 while 循环。

你只有通过调用 break 才能跳出 while True: 循环。

用一个 while 循环就可以了,里面用 if 条件来分开不同的情况。

撰写回答