0

我正在尝试制作一种视觉节拍器,在其中按下按钮以更改 bpm。一旦 bpm 为 85,如果再次按下按钮,则返回默认 bpm(120)。这是我 的代码:

from gpiozero import *
from time import sleep

bpmButton = Button(6)
bpmLED = LED(14)

#This function defines the flashing light
def lightFlash(luz, tiempoOn, rate):
    luz.on()
    sleep(tiempoOn)
    luz.off()
    sleep(rate-tiempoOn)

#This changes the flashing light according to the bpm
def bpmIndicator(bpm):
    durFlash = 60 / bpm
    durLuz = 0.2
    lightFlash(bpmLED, durLuz, durFlash)
    
#Initial bpm
currentBpm = 120


while True: 
    
    if bpmButton.is_pressed:
        currentBpm -= 5 
    if currentBpm < 80:
        currentBpm= 120
print(currentBpm)
bpmIndicator(currentBpm)

这有效。但是,当我尝试将“while”循环中的内容放入函数中时,它不再起作用了。我似乎无法存储新currentBpm值。这是我尝试将其转换为函数的尝试。

def bpmChanger(bpm):
    if bpmButton.is_pressed:
        bpm -= 5    
        if bpm < 80:
            bpm= 120
    print(bpm)
    return(bpm)
    
currentBpm = 120


while True: 
    
    bpmIndicator(bpmChanger(currentBpm))

我想保存任何bpmChanger返回的值,因为我计划稍后在项目中使用它。

4

1 回答 1

0

如前所述,您必须告诉 python,您想从函数外部使用“bpmButton”变量。因为否则python会实例化一个具有相同名称但没有值的新变量。尝试这个:

def bpmChanger(bpm):
  global bpmButton  # EDIT
  if bpmButton.is_pressed:
     bpm -= 5    
  if bpm < 80:
     bpm= 120
  print(bpm)

  return(bpm)
于 2021-02-27T18:27:30.093 回答