0

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.

1
  • You need to save the returned result to currentBpm, like currentBpm=BpmChanger(currentBpm) Also at the moment your function assumed bpmButton is a global - globals aren’t a good design choice, you could pass this into the bpmChanger function so it isn’t accessed as a global. Commented Jan 30, 2021 at 10:17

1 Answer 1

0

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.