micropython timing metronome

RP2040 based microcontroller boards running MicroPython.
Target audience: MicroPython users with an RP2040 boards.
This does not include conventional Linux-based Raspberry Pi boards.
Post Reply
classy_coder
Posts: 1
Joined: Wed Aug 24, 2022 2:39 am

micropython timing metronome

Post by classy_coder » Wed Aug 24, 2022 2:44 am

Hello,
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



User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: micropython timing metronome

Post by jimmo » Fri Aug 26, 2022 2:31 pm

classy_coder wrote:
Wed Aug 24, 2022 2:44 am
Can anyone point me in the right direction?
Hi,
It looks like you're using CircuitPython, not MicroPython
Might be worth trying the Adafruit discord: https://discord.com/invite/5FBsBHU

Post Reply