首页 > 解决方案 > 在多种功能中使用相同的基于加速度计的触发器

问题描述

使用带有内置加速度计的 Raspberry Pi 和 SenseHat 我正在尝试制作一个小游戏。游戏的不同部分都在函数内部,我希望玩家翻转他们的 Pi 以在这些部分之间进行。在链接的代码中,我已经隔离了我想要的,即调用一个函数并且在检测到运动之前不前进到下一个函数。如果您只使用一次,这非常有用,但尝试多次使用它并不能按预期工作。一旦 z == -1 的第一个 if 语句(pi 被翻转)被触发,它就会移动到下一个函数,并且不管它的方向如何,就好像它仍然在 z == -1 处一样。因此,即使您在程序开始时只翻转了一次 pi,它也会遍历所有使用该动作进行的功能。

from sense_hat import SenseHat
from time import sleep
​
sense = SenseHat()
seq = 0
​
#this will loop at the start until z is - 1, then it will change seq to 1 triggering the next function "testb()"
def testa(): 
    print("a")
    sleep(.5)
    if z == -1:
        global seq
        seq= 1
        
#this should loop printing b over and over until the Pi is flipped a second time and z = -1 again
#(but it doesnt it prints b once then changes seq to 2 no matter it's position)
def testb():
    print("b")
    sleep(1)
    if z == -1:
        global seq
        seq= 2
        
#same thing here, prints c once and changes the seq variable no matter the position        
def testc():
    print("c")
    sleep(1)
    if z == -1:
        global seq
        seq= 3
​​
while True:
    acceleration = sense.get_accelerometer_raw()
    z = acceleration['z']
​
    z=round(z, 0)
​
#at the beginning run testa()
    if seq == 0:
        testa()
​
#until seq is changed to 1, then run testb()
    if seq == 1:
        testb()
        
#until seq is changed to 2, then run testc()        
    if seq == 2:
        testc()
#until seqi is changed to  3, then print "done done done"        
    if seq == 3:
        print("done done done")

有谁知道如何避免这种情况?也许是一种在功能之间重置方向的方法?任何想法或帮助都非常感谢!

标签: pythonraspberry-pi

解决方案


推荐阅读