I have a problem in Python for a RaspberryPi program. In this continuous loop it will detect a change in one of the pins and will then open another pin + request a URL.
This works but the URL is being triggered all the time. So I want to optimize the loop to have the URL request only on change.
If found Dectecting a value change in Python loop but I could not get it to work properly.
Can you help me with this? Thanks in advance! Your help is much appreciated :)
P.S. If the urllib code can be optimized, please let me know. I'm getting to know Python more day-by-day #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()