pythonraspberry-pigpiozero

Raspberry Pi + GPIOzero: press button to change a variable in a loop (while the loop keeps on running)


I'm trying to make a visual metronome of sorts in which I press a button in order to change the bpm. Once the bpm is 85, if the button is pressed once more, if goes back to the default bpm (of 120). t this is my code:

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)

And this works. However, when I try putting whats in the "while" loop in a function it doesn't work anymore. I don't seem to be able to store the new currentBpm value. Here's my attempt at trying to convert it into a function.

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))

I'd like to save whatever value bpmChanger returns, as I plan on using it later on in the project.


Solution

  • As mentioned you have to tell python, that you want to use the "bpmButton" variable from outside the function. Because otherwise python instantiates a new variable with the same name, but no value. Try this:

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