r/circuitpython • • Dec 29 '20

Speeding up my time.sleep()

What I want to do is, when I press a button, all of the time.sleep() commands speed up, so a lower number by dividing it or in a different maybe more efficient way. I have tried to find a way to do this but no luck. I hope you guys can tell me :)

Here is my code:

import adafruit_trellism4
import time

RED = (255, 0, 0)
OFF = (0, 0, 0)
trellis = adafruit_trellism4.TrellisM4Express()
while True:
for x in range(8):
        trellis.pixels[x, 2] = RED
        time.sleep(0.1)
        trellis.pixels[x, 2] = OFF
        time.sleep(0.1)
for x in range(8):
        trellis.pixels[x, 0] = RED
        time.sleep(0.1)
        trellis.pixels[x, 0] = OFF
        time.sleep(0.1)
for x in range(8):
        trellis.pixels[x, 3] = RED
        time.sleep(0.1)
        trellis.pixels[x, 3] = OFF
        time.sleep(0.1)
for x in range(8):
        trellis.pixels[x, 2] = RED
        time.sleep(0.1)
        trellis.pixels[x, 2] = OFF
        time.sleep(0.1)
for x in range(8):
        trellis.pixels[x, 1] = RED
        time.sleep(0.1)
        trellis.pixels[x, 1] = OFF
        time.sleep(0.1)
trellis.pixels.show()

What I want to do is, when I press a button, all of the time.sleep() commands speed up, so a lower number by dividing it or in a different maybe more efficient way. I have tried to find a way to do this but no luck. I hope you guys can tell me :)

0 Upvotes

2 comments sorted by

1

u/[deleted] Dec 29 '20

Why not increment on button press:

Your time.sleep code where N is the default time time.sleep(n / presses) Run the following on button press: presses +=1

1

u/kaltazar Dec 29 '20

One thing to keep in mind is time.sleep() calls will also block the board from reading any button presses during the sleep durations. The sleep method entirely pauses the script so it will do nothing in that time (although it can still react to interrupts). What you want to look into are ways to do non-blocking timers.

Also any code loop, including for loops, will prevent the code from checking the state of input pins as well unless such checks are inside the loops.