Skip to content

Commit 6582ddb

Browse files
Update the millis() function to work with CircuitPython
time.time() was yielding integer number of seconds on CircuitPython. This made subsequent calls to millis() yield the same result leading to a divide by 0 issue when doing millis() - startTime()
1 parent d5265f1 commit 6582ddb

File tree

3 files changed

+12
-18
lines changed

3 files changed

+12
-18
lines changed

examples/ex2_Presence_Sensing.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,13 @@
5151
import time
5252
import sys
5353

54-
# Define a function to get milliseconds. This depends on the platform
55-
if hasattr(time, "ticks_ms"):
56-
# MicroPython: time.time() gives an integer, have to instead use ticks_ms()
54+
# Provide platform-dependent way to get current time in milliseconds
55+
if hasattr(time, "monotonic_ns"):
5756
def millis():
58-
return time.ticks_ms()
57+
return time.monotonic_ns() // 1000000 # works in CircuitPython and Linux/Raspberry Pi
5958
else:
60-
# Other platforms: time.time() gives a float
6159
def millis():
62-
return int(round(time.time() * 1000))
60+
return time.time_ns() // 1000000 #only works in MicroPython
6361

6462
def runExample():
6563

examples/ex5_HeartRate.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,13 @@
5656
import time
5757
import sys
5858

59-
# Define a function to get milliseconds. This depends on the platform
60-
if hasattr(time, "ticks_ms"):
61-
# MicroPython: time.time() gives an integer, have to instead use ticks_ms()
59+
# Provide platform-dependent way to get current time in milliseconds
60+
if hasattr(time, "monotonic_ns"):
6261
def millis():
63-
return time.ticks_ms()
62+
return time.monotonic_ns() // 1000000 # works in CircuitPython and Linux/Raspberry Pi
6463
else:
65-
# Other platforms: time.time() gives a float
6664
def millis():
67-
return int(round(time.time() * 1000))
65+
return time.time_ns() // 1000000 #only works in MicroPython
6866

6967
def runExample():
7068

examples/ex6_FIFO_Readings.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,13 @@
5252
import time
5353
import sys
5454

55-
# Define a function to get milliseconds. This depends on the platform
56-
if hasattr(time, "ticks_ms"):
57-
# MicroPython: time.time() gives an integer, have to instead use ticks_ms()
55+
# Provide platform-dependent way to get current time in milliseconds
56+
if hasattr(time, "monotonic_ns"):
5857
def millis():
59-
return time.ticks_ms()
58+
return time.monotonic_ns() // 1000000 # works in CircuitPython and Linux/Raspberry Pi
6059
else:
61-
# Other platforms: time.time() gives a float
6260
def millis():
63-
return int(round(time.time() * 1000))
61+
return time.time_ns() // 1000000 #only works in MicroPython
6462

6563
def runExample():
6664

0 commit comments

Comments
 (0)