在 while 循环中重置变量的计数

Resetting the count of variable in a while loop

from microbit import *
from ssd1306 import initialize, clear_oled
from ssd1306_stamp import draw_stamp
from ssd1306_img import create_stamp
from ssd1306_text import add_text
import utime as time
window = []  
threshold = 550  # limit
count = 0 
sample = 0 
beat = False  
start = False
good = create_stamp(Image.HAPPY)
bad = create_stamp(Image.SAD)
heart = create_stamp(Image.HEART)
values = []  
def mean(datalist):
    sum = 0 
    for i in datalist:  
        sum += i 
    if len(datalist) > 0:  
        return sum/len(datalist)  
    else:
        return None 
while True:
    if button_a.was_pressed():
        while True:
            signal = pin1.read_analog()   
            window.append(signal)  
            avg = round(mean(window)) 
            values.append(avg) 
            if len(window) == 11:    
                window.pop(0)  
            if beat is False and avg >= threshold+10:
                beat = True 
                count += 1  
                display.show(Image.HEART, wait=False) 
                if count == 1:  
                    t1 = time.ticks_ms() 
                if count == 11:  
                    t2 = time.ticks_ms()  
                    T = t2 - t1     
                    bpm = round(600*1000/(T)) 
                    display.scroll(str(bpm)) 
                    initialize()
                    clear_oled()
                    add_text(0, 0, "Heart rate :")
                    add_text(0, 3, str(bpm) + " bpm")
                    if 60 <= bpm <= 100:
                        draw_stamp(38, 24, good, 1)
                    else :
                        draw_stamp(38, 24, bad, 1)
                    count = 0  
                    sleep(2000)
                if button_b.was_pressed():
                    break
                    count = 0
            elif beat is True and avg <= threshold-10:
                beat = False 
                display.clear()  
                sample += 1  
            if sample == 250:  
                threshold = mean(values)
                values = []  
                sample = 0  
            sleep(20)  
        sleep(20)  

这是连接microbit的代码,功能是关于心率传感器,当检测到10次心跳时,会出现每分钟的平均心跳数。

我想增加一个功能,如果按下按钮b,循环会暂停,然后按下按钮a重新开始。我试图在循环中添加一个中断功能,当我点击按钮 b 时它起作用了,它暂停了循环,但是,节拍数不会重置,并且虽然我打破了循环,但节拍之间的时间也会被记录下来.

有什么方法可以打破循环并重置计数?

你应该在破解前重置计数器。在您当前的代码中,计数行未执行,因为它在到达之前就中断了。

if button_b.was_pressed():
    count = 0
    break