简体   繁体   中英

how can i make my script continuously run

I have made the connections in my board where I read the state of a reed switch. When the magnet nearby it shows "0" and I store the data at the "x" variable.

I'm using this to read the state of a fridge door so I can control some relays when the door is open (0) and then turn it off when closed (1).

When I use a while loop, I get the script running but it keeps counting when the variable is 1. I need this script to count when the door opens, (one) closes, and opens again (two).

Here is the code so far with the while loop.

import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)


inPin=15
outPin=12

GPIO.setup(inPin,GPIO.IN)
GPIO.setup(outPin,GPIO.OUT)

counter = 0

while True:

    x = GPIO.input(inPin)
    previousValue = 0

    print(x)
    if x==1:
        GPIO.output(outPin,GPIO.LOW)
    if x==0:
        GPIO.output(outPin,GPIO.HIGH)
    
    if x == 1 and previousValue == 0:
        counter += 1
        print(counter)

You could change the previous value

    if x == 1 and previousValue == 0:
        counter += 1
        print(counter)
        previousValue == 1
    elif x == 0 and previousValue == 1:
        previousValue == 0

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM