I'm fairly new to this fun world. I am trying to start with a metronome project. The way I would like to do that is by tracking a button that is pushed 4 times, and averaging out the time between button pushes to set the tempo. I'm not sure what library I would use to do that and how to set it. I was thinking of an array for each button push until the fourth, and setting the average that way in miliseconds.
Can anyone point me in the right direction?
Code: Select all
import time
import board
#import touchio
from digitalio import DigitalInOut, Direction, Pull
# starting counter
n = 0
#start counting time
#startTime = time.ticks_ms()
blocks = [0, 0, 0, 0, 0]
startTime = 0
endTime = 0
d = 0
btn = DigitalInOut(board.D0)
btn.direction = Direction.INPUT
btn.pull = Pull.UP
prev_state = btn.value
vib = DigitalInOut(board.D2)
vib.direction = Direction.OUTPUT
while True:
cur_state = btn.value
if cur_state != prev_state:
if not cur_state:
startTime = time.monotonic()
d = startTime - endTime
n = n + 1
print(d)
else:
n = n
endTime = time.monotonic()
prev_state = cur_state
if n < 5:
blocks[n] = d
else:
avg = float(blocks[2] + blocks[3] + blocks[4])/3
print(blocks)
print("\n")
print("the average is " + str(avg))
time.sleep(1)
while n == 4:
avg = float(blocks[2] + blocks[3] + blocks[4])/3
vib.value = True
time.sleep(0.2)
vib.value = False
time.sleep(avg-0.2)
if cur_state != prev_state:
n=0
prev_state = cur_state