Raspberry Pi + GPIOzero:按下按钮在循环中更改变量同时循环继续运行

问题描述

我正在尝试制作一种视觉节拍器,我可以在其中按下按钮以更改 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)

这是有效的。但是,当我尝试将 whats 放入函数的“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 返回的任何值,因为我计划稍后在项目中使用它。

解决方法

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

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

  return(bpm)