#request for comments

1 messages · Page 1 of 1 (latest)

rough aspen
#

Can you explain this code? I'm struggling with it. It seems really dense. Like I don't understand the brackets.

#

@alpine gyro

cosmic shale
#

it's setting the timestamp associated with the key when you press the key, then in every loop it does something based on the time value

alpine gyro
#

keys_pressed is a list -- one entry per key.

#

in the while loop it updates key_pressed when an event occurs

#

with keys_pressed updated you can use it to check if a key is pressed and if so how long it has been pressed

cosmic shale
#

your code could then work like that:

keys_pressed = [0] * 12
while True:
    ev = pad.keys.events.get()
    if ev:
        if ev.pressed and not keys_pressed[ev.key_number]:
            keys_pressed[ev.key_number] = time.monotonic()
        elif ev.released:
            keys_pressed[ev.key_number] = 0

    for key_num, timestamp in enumerate(keys_pressed):
        if timestamp > 0: # that key is pressed
            time_pressed = time.monotonic() - timestamp
            if key_num == 0: # key 0
                if time_pressed < .75: # pressed less than 750ms
                    m.move(0,3,0)
                    print('medium')
                else: # pressed longer
                    m.move(0,7,0)
                    print('fast!')
alpine gyro
#

supervisor.ticks_ms() should be used
time_pressed = supervisor.ticks_ms() - timestamp

cosmic shale
#

nah, you can't do that

#

here is how you would do it with the event.timestamp:

from adafruit_ticks import ticks_ms, ticks_diff
keys_pressed = [0] * 12
while True:
    ev = pad.keys.events.get()
    if ev:
        if ev.pressed and not keys_pressed[ev.key_number]:
            keys_pressed[ev.key_number] = ev.timestamp
        elif ev.released:
            keys_pressed[ev.key_number] = 0

    for key_num, timestamp in enumerate(keys_pressed):
        if timestamp > 0: # that key is pressed
            now = ticks_ms()
            if key_num == 0: # key 0
                if ticks_diff(now, timestamp) < 750: # pressed less than 750ms
                    m.move(0,3,0)
                    print('medium')
                else: # pressed longer
                    m.move(0,7,0)
                    print('fast!')
#

because ticks_ms loops back

#

it's meant to fit without long ints

alpine gyro
#

Yeah that would have to be handled.

#

handy to know about adafruit_ticks -- I hadn't seen that before

rough aspen
#

Adafruit_ticks is underrated and I really enjoy using it and need to add the syntax to my notebook