Search code examples
pythonraspberry-pipygamesensorsgpio

Python: Make a boolean change from True to False after a few seconds


I have this code I'm working on for a basketball game (sort of an arcade style basketball game using a vibration sensor and an HC-SR04 for detecting backboard hits and scored shots). I'm trying to figure out how to have a global boolean change from True to False after a few seconds has passed.

So for example, the ball hits the backboard--which sets the gobal backboard to True--from there it would stay True for a few seconds more to see if the ball bounced from the backboard into the net. If the backboard variable is still true when the ball goes through the net than it would know its an off the backboard shot and could play a special sound effect of some other cool things.

Right now in the callback function the backboard variable is set to True when the ball hits the backboard, but it will just stay True until the player scores instead of changing back to false after a few seconds.

Here is the code:

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

Solution

  • I suggest simply implementing a timer object. Try implementing this:

    from threading import Timer
    import time
    
    def switchbool():
        backboard = false
    
    t = Timer(3.0, switchbool) #will call the switchbool function after 3 seconds
    t.start()
    

    Simply create a timer object like the one in the above example whenever the ball hits the backboard(whenever you set backboard = true).