Python:几秒钟后从True变为False
问题描述:
我有这个代码我正在为一个篮球比赛(使用振动传感器和HC-SR04检测篮板的街机风格的篮球比赛命中和得分镜头)。我试图弄清楚在几秒钟后如何将全局布尔变化从True变为False。因此,例如,球击中背板 - 将背部板设置为真(True) - 从那里它将保持真实几秒钟以上,以查看球是否从背板弹回到网中。如果球穿过网球时篮板变量仍然是真实的,而不是知道它在篮板上的射门,并且可以发挥其他一些很酷的东西的特殊效果。Python:几秒钟后从True变为False
现在在回调函数中,当球击中篮板时,背板变量设置为真,但它将保持为真,直到玩家分数,而不是在几秒钟后变回假。
下面是代码:
import RPi.GPIO as GPIO
from gpiozero import DistanceSensor
import pygame
import time
ultrasonic = DistanceSensor(echo=17, trigger=4)
ultrasonic.threshold_distance = 0.3
pygame.init()
#Global
backboard = False
#GPIO SETUP
channel = 22
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)
#music
score = pygame.mixer.Sound('net.wav')
bb = pygame.mixer.Sound("back.wav")
def scored():
#the ball went through the net and trigged the HC-SR04
global backboard
if backboard == True:
print("scored")
backboard = False
score.play()
time.sleep(0.75)
else:
print("scored")
score.play()
time.sleep(0.75)
def callback(channel):
#the ball hit the backboard and triggered the vibration sensor
global backboard
if GPIO.input(channel):
backboard = True
print("backboard")
bb.play()
time.sleep(0.75)
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300) # let us know when the pin goes HIGH or LOW
GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN, Run function on change
ultrasonic.when_in_range = scored
答
我建议只是实现一个计时器对象。尝试实现这个:
from threading import Timer
import time
def switchbool():
backboard = false
t = Timer(3.0, switchbool) #will call the switchbool function after 3 seconds
每当球击中篮板简单地创建像在上面的例子中的定时器对象(只要你设置篮板= TRUE)。
+0
辉煌的修正,这似乎是工作真的很好! –
了。在我的代码的最后一行一个错字 - ultrasonic.when_in_range =得分() 应该是: ultrasonic.when_in_range =进球 。这是现在上面 –