raspberry pi - Python: Make a boolean change from True to False after a few seconds -
i have code i'm working on basketball game (sort of arcade style basketball game using vibration sensor , hc-sr04 detecting backboard hits , scored shots). i'm trying figure out how have global boolean change true false after few seconds has passed.
so example, ball hits backboard--which sets gobal backboard true--from there stay true few seconds more see if ball bounced backboard net. if backboard variable still true when ball goes through net know off backboard shot , play special sound effect of other cool things.
right in callback function backboard variable set true when ball hits backboard, stay true until player scores instead of changing false after few seconds.
here code:
import rpi.gpio gpio 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 net , trigged 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 backboard , triggered 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 know when pin goes high or low gpio.add_event_callback(channel, callback) # assign function gpio pin, run function on change ultrasonic.when_in_range = scored
i suggest implementing timer object. try implementing this:
from threading import timer import time def switchbool(): backboard = false t = timer(3.0, switchbool) #will call switchbool function after 3 seconds
simply create timer object 1 in above example whenever ball hits backboard(whenever set backboard = true).
Comments
Post a Comment