Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

python - 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.

question from:https://stackoverflow.com/questions/65943447/raspberry-pi-gpiozero-press-button-to-change-a-variable-in-a-loop-while-the

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...