使用urllib.urlopen调用了两次函数

2024-06-28 19:15:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一小段代码检测我的树莓特定GPIO上的事件。当检测到事件时,如果在函数中我只保留“print('Flash…'),则调用名为increase\u counter的函数我每个事件只有一次打印,但是如果我用urllib2调用一个url,整个increase\u计数器将执行两次,因此我将有2次闪烁计数

import RPi.GPIO as GPIO
import time
import urllib2,json

def increase_counter(ch):
    print('Flash ... ')
    requete='http://192.168.1.20:8080/json.htm?type=command&param=udevice&idx=52&svalue=1'
    response=urllib2.urlopen(requete)
    data = json.loads(response.read())
    print data

IRPIN = 4


GPIO.setmode(GPIO.BCM) #GPIO SETUP
GPIO.setup(IRPIN,GPIO.IN) #GPIO SETUP

GPIO.add_event_detect(IRPIN, GPIO.FALLING, callback=increase_counter, bouncetime=3) #Calling event when flash is detected

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print(' Stopped !!!')
except:
    print(' Stopped !!!')
    raise
finally:
    GPIO.remove_event_detect(IRPIN)
    GPIO.cleanup(IRPIN) # GPIO cleanup

Tags: 函数importeventjsongpiotimeresponsecounter