Skip to content

Commit bc1a666

Browse files
committed
Improved sleep_for, allows alarms up to 28 days long
1 parent fa01a17 commit bc1a666

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

firmware/PIMORONI_BADGER2040W/lib/badger2040.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -138,17 +138,21 @@ def sleep_for(minutes):
138138
if second >= 55:
139139
minute += 1
140140

141-
minute += minutes
141+
# Can't sleep beyond a month, so clamp the sleep to a 28 day maximum
142+
minutes = min(minutes, 40320)
142143

143-
while minute >= 60:
144-
minute -= 60
145-
hour += 1
144+
# Calculate the future alarm date; first, turn the current time into seconds since epoch
145+
sec_since_epoch = time.mktime((year, month, day, hour, minute, second, dow, 0))
146146

147-
if hour >= 24:
148-
hour -= 24
147+
# Add the required minutes to this
148+
sec_since_epoch += minutes * 60
149149

150+
# And convert it back into a more useful tuple
151+
(ayear, amonth, aday, ahour, aminute, asecond, adow, adoy) = time.localtime(sec_since_epoch)
152+
153+
# And now set the alarm as before, now including the day
150154
rtc.clear_alarm_flag()
151-
rtc.set_alarm(0, minute, hour)
155+
rtc.set_alarm(0, aminute, ahour, aday)
152156
rtc.enable_alarm_interrupt(True)
153157

154158
turn_off()

0 commit comments

Comments
 (0)