Python:几秒钟后将布尔值从True更改为False

2024-09-29 17:09:22 发布

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

我有这个代码,我正在为一个篮球比赛(一种街机风格的篮球游戏,使用振动传感器和HC-SR04来检测篮板命中率和得分率)。我想弄清楚如何在几秒钟后将全局布尔值从True更改为False。在

举个例子,球撞到了篮板上——这就把球的篮板设置成了真的——从那里再保持几秒钟,看看球是不是从篮板反弹到了网里。如果篮板变量仍然是真的,当球通过网,那么它就会知道这是一个离篮板投篮,可以发挥一些其他酷东西的特殊声音效果。在

现在在回调函数中,当球碰到篮板时,backboard变量被设置为True,但它将保持为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

Tags: theimportfalsetruegpiotimechannelpygame
1条回答
网友
1楼 · 发布于 2024-09-29 17:09:22

我建议简单地实现一个timer对象。试着实现这一点:

from threading import Timer
import time

def switchbool():
    backboard = false

t = Timer(3.0, switchbool) #will call the switchbool function after 3 seconds

只要创建一个计时器对象,就像上面例子中的对象,只要球碰到篮板(只要设置backboard=true)。在

相关问题 更多 >

    热门问题