检测RaspberryPi的Python循环更改

时间:2017-08-08 11:02:43

标签: python raspberry-pi

我在Python中遇到RaspberryPi程序的问题。 在这个连续循环中,它将检测其中一个引脚的变化,然后打开另一个引脚+请求一个URL。

这有效,但URL一直在被触发。所以我想优化循环以仅在更改时获得URL请求。

如果找到Dectecting a value change in Python loop,但我无法正常使用。

你能帮我解决这个问题吗?提前致谢!非常感谢您的帮助:)

P.S。如果urllib代码可以优化,请告诉我。我逐日了解Python #beginner;)

#!/usr/bin/env python

import time
import urllib2
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(26, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(24, GPIO.OUT)

GPIO.output(24, GPIO.LOW)

username = "some"
password = "one"

while True:
    if GPIO.input(26):
        GPIO.output(24, GPIO.HIGH)
        password_mgr1 = urllib2.HTTPPasswordMgrWithDefaultRealm()
        top_level_url1 = "http://192.168.x.x/dev/sps/io/VI7/On"
        password_mgr1.add_password(None, top_level_url1, username, password)
        handler1 = urllib2.HTTPBasicAuthHandler(password_mgr1)
        opener1 = urllib2.build_opener(handler1)
        opener1.open(top_level_url1)

    else:
        GPIO.output(24, GPIO.LOW)
        password_mgr2 = urllib2.HTTPPasswordMgrWithDefaultRealm()
        top_level_url2 = "http://192.168.x.x/dev/sps/io/VI7/Off"
        password_mgr2.add_password(None, top_level_url2, username, password)
        handler2 = urllib2.HTTPBasicAuthHandler(password_mgr2)
        opener2 = urllib2.build_opener(handler2)
        opener2.open(top_level_url2)
        time.sleep(5)

GPIO.cleanup()

2 个答案:

答案 0 :(得分:0)

我几乎从不编写python代码但是下面的内容(它可能有语法错误,但你得到了要点)

#!/usr/bin/env python

import time
import urllib2
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(26, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(24, GPIO.OUT)

GPIO.output(24, GPIO.LOW)

username = "some"
password = "one"
lastState = False
while True:
    state = GPIO.input(26)
    if (state != lastState):
        lastState = state
        if state:
            GPIO.output(24, GPIO.HIGH)
            password_mgr1 = urllib2.HTTPPasswordMgrWithDefaultRealm()
            top_level_url1 = "http://192.168.x.x/dev/sps/io/VI7/On"
            password_mgr1.add_password(None, top_level_url1, username, password)
            handler1 = urllib2.HTTPBasicAuthHandler(password_mgr1)
            opener1 = urllib2.build_opener(handler1)
            opener1.open(top_level_url1)

        else:
            GPIO.output(24, GPIO.LOW)
            password_mgr2 = urllib2.HTTPPasswordMgrWithDefaultRealm()
            top_level_url2 = "http://192.168.x.x/dev/sps/io/VI7/Off"
            password_mgr2.add_password(None, top_level_url2, username, password)
            handler2 = urllib2.HTTPBasicAuthHandler(password_mgr2)
            opener2 = urllib2.build_opener(handler2)
            opener2.open(top_level_url2)
            time.sleep(5)

GPIO.cleanup()

答案 1 :(得分:0)

只需添加一个存储值,如果值已更改:

# [...]

haschanged = False

while True:
    if GPIO.input(26):
        if haschanged:
            continue
        haschanged = True
        # [...]
    else:
        haschanged = False
        # [...]
# [...]