我有這個代碼我正在爲一個籃球比賽(使用振動傳感器和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
了。在我的代碼的最後一行一個錯字 - ultrasonic.when_in_range =得分() 應該是: ultrasonic.when_in_range =進球 。這是現在上面 –