Skip to content

Instantly share code, notes, and snippets.

@stonehippo
Last active November 30, 2025 03:59
Show Gist options
  • Select an option

  • Save stonehippo/6277d19ac915194e262e257e41c3262b to your computer and use it in GitHub Desktop.

Select an option

Save stonehippo/6277d19ac915194e262e257e41c3262b to your computer and use it in GitHub Desktop.
Simple non-blocking timing in CircuitPython
'''
This is an implementation of some simple, non-blocking timers for CircuitPython.
The 'timer' is just a time value and some methods to return state based on
whatever intervals seem appropriated. It's based on adafruit_ticks and will overflow
in the same way as the underlying methods (https://docs.circuitpython.org/projects/ticks/en/latest/index.html)
Where possible, you should probably consider using asyncio. This implementation
is lightweight, but it may not produce precise results or consistent timing.
This is a re-write of some code that I originally wrote to make non-blocking
timers in Arduino code.
For details, see https://github.com/stonehippo/arduino-helpers?tab=readme-ov-file#timinghelpersh
'''
from adafruit_ticks import ticks_ms, ticks_diff
def is_timer_running(timer):
return timer != 0
def clear_timer():
return 0
def start_timer():
return ticks_ms()
def is_timer_expired(timer, expiration):
current = ticks_diff(ticks_ms(), timer)
return current > expiration
import timing_helpers as th
# initialize three timers
timer_1, timer_2, timer_3 = (0, 0, 0)
# encapsulate the logic for checking and managing timer
def check_timer(timer, msg, expiration=1000):
if not th.is_timer_running(timer):
return th.start_timer()
if th.is_timer_expired(timer, expiration):
print(msg)
return th.clear_timer()
else:
return timer
while True:
timer_1 = check_timer(timer_1, "One!") # fires every second
timer_2 = check_timer(timer_2, "Two!", 3000) # fires every three seconds
timer_3 = check_timer(timer_3, "Three!", 1500) # fires every 1.5 seconds
import timing_helpers as th
# initialize a timer
timer = 0
while True:
# if the timer has never started, or has been cleared, fire it up
if not th.is_timer_running(timer):
timer = th.start_timer()
# to see if about 1.5 seconds have passed
if th.is_timer_expired(timer, 1500):
print("Ding!")
# reset the timer; it will get started on the next pass
timer = th.clear_timer()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment