Python pyb.RTC Examples
The following are 30
code examples of pyb.RTC().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pyb
, or try the search function
.
Example #1
Source File: pbmqtt.py From micropython-mqtt with MIT License | 7 votes |
def _do_rtc(self): lnk = self._lnk lnk.vbprint('Start RTC synchroniser') self._time_valid = not self._rtc_last_syn == 0 # Valid on restart while True: while not self._time_valid: lnk.channel.send(TIME) # Give 5s time for response await asyn.sleep(5) if not self._time_valid: # WiFi may be down. Delay 1 min before retry. await asyn.sleep(60) else: # Valid time received or restart if self._rtc_interval < 0: break # One resync only: done tend = self._rtc_last_syn + self._rtc_interval twait = max(tend - time(), 5) # Prolonged outage await asyn.sleep(twait) self._time_valid = False
Example #2
Source File: pbmqtt.py From micropython-mqtt with MIT License | 6 votes |
def _do_time(self, action): # TIME received from ESP8266 lnk = self._lnk try: t = int(action[0]) except ValueError: # Gibberish. lnk.quit('Invalid data from ESP8266') return self._time_valid = t > 0 if self._time_valid: rtc = pyb.RTC() tm = localtime(t) hours = (tm[3] + self._local_time_offset) % 24 tm = tm[0:3] + (tm[6] + 1,) + (hours,) + tm[4:6] + (0,) rtc.datetime(tm) self._rtc_last_syn = time() lnk.vbprint('time', localtime()) else: lnk.vbprint('Bad time received.') # Is Pyboard RTC synchronised?
Example #3
Source File: bluest_protocol.py From uble with MIT License | 6 votes |
def __init__(self, *args, **kwargs): super(BlueSTProtocol, self).__init__(*args, **kwargs) self.rtc = pyb.RTC() self.rtc.init() self.rtc.calibration(-129) self.rtc.datetime((2017, 10, 6, 5, 16, 41, 0, 0)) self.bdaddr = bytes(reversed([0x12, 0x34, 0x00, 0xE1, 0x80, 0x02])) self.name = b'PyBLE' self.connection_handle = None self.service_handle = None self.dev_name_char_handle = None self.appearance_char_handle = None self.hw_serv_handle = None self.acc_gyro_mag_bluest_char_handle = None self.pressure_bluest_char_handle = None self.temperature_bluest_char_handle = None self.pwr_bluest_char_handle = None
Example #4
Source File: rtc_time.py From micropython-async with MIT License | 6 votes |
def _run(self): print('Low power mode is ON.') rtc = pyb.RTC() rtc.wakeup(self._t_ms) t_ms = self._t_ms while True: if t_ms > 0: pyb.stop() # Pending tasks run once, may change self._t_ms yield if t_ms != self._t_ms: # Has changed: update wakeup t_ms = self._t_ms if t_ms > 0: rtc.wakeup(t_ms) else: rtc.wakeup(None)
Example #5
Source File: as_tGPS.py From micropython-async with MIT License | 6 votes |
def calibrate(self, minutes=5): if not on_pyboard: raise OSError('Only available on STM targets.') print('Waiting for GPS startup.') await self.ready() print('Waiting up to {} minutes to acquire calibration factor...'.format(minutes)) cal = await self._getcal(minutes) if cal <= 512 and cal >= -511: rtc.calibration(cal) print('Pyboard RTC is calibrated. Factor is {:d}.'.format(cal)) else: print('Calibration factor {:d} is out of range.'.format(cal)) # User interface functions: accurate GPS time. # Return GPS time in ms since midnight (small int on 32 bit h/w). # No allocation.
Example #6
Source File: shell.py From upy-shell with MIT License | 6 votes |
def do_set_time(self, line): args = split_line(line) if (len(args) != 6): self.stderr.write('Expecting 6 arguments in the order: YYYY MM DD HH MM SS\n') return try: (year, month, day, hours, minutes, seconds) = [int(arg) for arg in args] except: self.stderr.write("Expecting numeric arguments\n") return # Run the date through mktime and back through localtime so that we # get a normalized date and time, and calculate the weekday t = time.mktime((year, month, day, hours, minutes, seconds, 0, 0, -1)) (year, month, day, hours, minutes, seconds, weekday, yearday) = time.localtime(t) rtc = pyb.RTC() # localtime weekday is 0-6, Monday is 0 # RTC weekday is 1-7, Monday is 1 rtc.datetime((year, month, day, weekday + 1, hours, minutes, seconds, 0)) self.stdout.write(ctime(time.time()))
Example #7
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _get_rtc_usecs(self): y, m, d, weekday, hrs, mins, secs, subsecs = rtc.datetime() tim = 1000000 * utime.mktime((y, m, d, hrs, mins, secs, weekday - 1, 0)) return tim + ((1000000 * (255 - subsecs)) >> 8) # Return no. of μs RTC leads GPS. Done by comparing times at the instant of # PPS leading edge.
Example #8
Source File: rtc_alarm.py From upy-examples with MIT License | 5 votes |
def set_alarm_3_seconds_in_future(): global alarm_fired rtc_time = list(rtc.datetime()) # The order of the fields in the RTC time differs from the order that mktime wants # We call mktime since it will re-normalize the time if the seconds goes # above 59 alarm_time = [rtc_time[0], rtc_time[1], rtc_time[2], rtc_time[4], rtc_time[5], rtc_time[6], 0, 0] alarm_time[5] += 3 # Set the alarm 3 seconds in the future alarm_time = time.localtime(time.mktime(alarm_time)) # Normalize in case seconds wrap alarm_min = alarm_time[4] alarm_sec = alarm_time[5] print('Setting alarm for {:02}:{:02}:{:02}'.format(alarm_time[3], alarm_time[4], alarm_time[5])) disable_write_protection() disable_alarm_a() wait_for_alarm_a_ready() alrmar = 0 alrmar |= RTC_ALRMAR_MSK4 # set MSK4 - date doesn't matter alrmar |= RTC_ALRMAR_MSK3 # set MSK3 - hours don't matter alrmar |= (alarm_min // 10) << RTC_ALRMAR_MNT_Pos # BCD tens of minutes alrmar |= (alarm_min % 10) << RTC_ALRMAR_MNU_Pos # BCD units of minutes alrmar |= (alarm_sec // 10) << RTC_ALRMAR_ST_Pos # BCD tens of seconds alrmar |= (alarm_sec % 10) << RTC_ALRMAR_SU_Pos # BCD units of seconds stm.mem32[stm.RTC + stm.RTC_ALRMAR] = alrmar stm.mem32[stm.RTC + stm.RTC_ALRMASSR] = 0 # No comparison on subseconds alrmar2 = stm.mem32[stm.RTC + stm.RTC_ALRMAR] & 0xffffffff if alrmar != alrmar2: print('#####') print('##### Setting ALRMAR failed alrmar = {:08x} alrmar2 = {:08x}'.format(alrmar, alrmar2)) print('#####') alarm_fired = False enable_alarm_a() enable_write_protection()
Example #9
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def delta(self): if not on_pyboard: raise OSError('Only available on STM targets.') rtc_time, gps_time = await self._await_pps() # μs since Y2K at time of latest PPS return rtc_time - gps_time # Pause until PPS interrupt occurs. Then wait for an RTC subsecond change. # Read the RTC time in μs since Y2K and adjust to give the time the RTC # (notionally) would have read at the PPS leading edge.
Example #10
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _await_pps(self): t0 = self.acquired while self.acquired == t0: # Busy-wait on PPS interrupt: not time-critical await asyncio.sleep_ms(0) # because acquisition time stored in ISR. gc.collect() # Time-critical code follows st = rtc.datetime()[7] while rtc.datetime()[7] == st: # Wait for RTC to change (4ms max) pass dt = utime.ticks_diff(utime.ticks_us(), self.acquired) trtc = self._get_rtc_usecs() - dt # Read RTC now and adjust for PPS edge tgps = 1000000 * (self.epoch_time + 3600*self.local_offset + 1) return trtc, tgps # Non-realtime calculation of calibration factor. times are in μs
Example #11
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _calculate(self, gps_start, gps_end, rtc_start, rtc_end): # Duration (μs) between PPS edges pps_delta = (gps_end - gps_start) # Duration (μs) between PPS edges as measured by RTC and corrected rtc_delta = (rtc_end - rtc_start) ppm = (1000000 * (rtc_delta - pps_delta)) / pps_delta # parts per million return int(-ppm/0.954) # Measure difference between RTC and GPS rate and return calibration factor # If 3 successive identical results are within 1 digit the outcome is considered # valid and the coro quits.
Example #12
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _getcal(self, minutes=5): if minutes < 1: raise ValueError('minutes must be >= 1') results = [0, 0, 0] # Last 3 cal results idx = 0 # Index into above circular buffer nresults = 0 # Count of results rtc.calibration(0) # Clear existing RTC calibration await self.set_rtc() # Wait for PPS, then RTC 1/256 second change. Return the time the RTC # would have measured at instant of PPS (notional μs since Y2K). Also # GPS time at the same instant. rtc_start, gps_start = await self._await_pps() for n in range(minutes): for _ in range(6): # Try every 10s await asyncio.sleep(10) # Get RTC time at instant of PPS rtc_end, gps_end = await self._await_pps() cal = self._calculate(gps_start, gps_end, rtc_start, rtc_end) print('Mins {:d} cal factor {:d}'.format(n + 1, cal)) results[idx] = cal idx += 1 idx %= len(results) nresults += 1 if nresults >= 4 and (abs(max(results) - min(results)) <= 1): return round(sum(results)/len(results)) return cal # Pause until time/date message received and 1st PPS interrupt has occurred.
Example #13
Source File: shell.py From upy-shell with MIT License | 5 votes |
def help_set_time(self): self.stdout.write('Sets the RTC time.\n' + 'set_time YYYY MM DD HH MM SS\n')
Example #14
Source File: sync_rtc.py From upy-examples with MIT License | 5 votes |
def set_time(rtc_time): import pyb rtc = pyb.RTC() rtc.datetime(rtc_time)
Example #15
Source File: rtc_alarm.py From upy-examples with MIT License | 5 votes |
def rtc_regs(): for name in ['TR', 'DR', 'CR', 'ISR', 'WUTR', 'ALRMAR', 'WPR', 'SSR', 'TAFCR', 'ALRMASSR']: offset = eval('stm.RTC_' + name) val = stm.mem32[stm.RTC + offset] & 0xffffffff print('{:8s} = {:08x}'.format(name, val))
Example #16
Source File: rtc_alarm.py From upy-examples with MIT License | 5 votes |
def disable_alarm_a(): rtc_cr = stm.mem32[stm.RTC + stm.RTC_CR] rtc_cr &= ~RTC_CR_ALRAE # Clear ALRAE (Alarm A Enable) stm.mem32[stm.RTC + stm.RTC_CR] = rtc_cr
Example #17
Source File: rtc_alarm.py From upy-examples with MIT License | 5 votes |
def enable_alarm_a(): rtc_isr = stm.mem32[stm.RTC + stm.RTC_ISR] rtc_isr &= ~RTC_ISR_ALRAF # Clear ALRAF stm.mem32[stm.RTC + stm.RTC_ISR] = rtc_isr rtc_cr = stm.mem32[stm.RTC + stm.RTC_CR] rtc_cr |= RTC_CR_ALRAE # Set ALRAE (Alarm A Enable) rtc_cr |= RTC_CR_ALRIE # Set ALRAIE (Alarm A Interrupt Enable) stm.mem32[stm.RTC + stm.RTC_CR] = rtc_cr
Example #18
Source File: rtc_alarm.py From upy-examples with MIT License | 5 votes |
def wait_for_alarm_a_ready(): while True: rtc_isr = stm.mem32[stm.RTC + stm.RTC_ISR] if (rtc_isr & RTC_ISR_ALRAWF) == 1: return
Example #19
Source File: rtc_alarm.py From upy-examples with MIT License | 5 votes |
def enable_write_protection(): stm.mem32[stm.RTC + stm.RTC_WPR] = 0xff if USE_DBP: pwr_cr = stm.mem32[stm.PWR + stm.PWR_CR] pwr_cr &= ~PWR_CR_DBP # Disable access to RTC & Backup registers stm.mem32[stm.PWR + stm.PWR_CR] = pwr_cr
Example #20
Source File: pbmqtt.py From micropython-mqtt with MIT License | 5 votes |
def default_status_handler(mqtt_link, status): await asyncio.sleep_ms(0) if status == SPECNET: if mqtt_link.first_run: mqtt_link.first_run = False return 1 # By default try specified network on 1st run only asyncio.sleep(30) # Pause before reboot. return 0 # Optionally synch the Pyboard's RTC to an NTP timeserver. When instantiated # is idle bar reporting synch status. _start runs _do_rtc coro if required.
Example #21
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _dtset(self, wday): t = self.epoch_time + int(3600 * self.local_offset) y, m, d, hrs, mins, secs, *_ = self._localtime(t) self._rtcbuf[0] = y self._rtcbuf[1] = m self._rtcbuf[2] = d self._rtcbuf[3] = wday self._rtcbuf[4] = hrs self._rtcbuf[5] = mins self._rtcbuf[6] = secs # Subsecs register is read-only. So need to set RTC on PPS leading edge. # Set flag and let ISR set the RTC. Pause until done.
Example #22
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _isr(self, _): acquired = utime.ticks_us() # Save time of PPS # Time in last NMEA sentence was time of last PPS. # Reduce to integer secs since midnight local time. isecs = (self.epoch_time + int(3600*self.local_offset)) % 86400 # ms since midnight (28 bits). Add in any ms in RMC data msecs = isecs * 1000 + self.msecs # This PPS is presumed to be one update later msecs += self._update_ms if msecs >= 86400000: # Next PPS will deal with rollover return if self.t_ms == msecs: # No RMC message has arrived: nothing to do return self.t_ms = msecs # Current time in ms past midnight self.acquired = acquired # Set RTC if required and if last RMC indicated a 1 second boundary if self._rtc_set: # Time as int(seconds) in last NMEA sentence. Earlier test ensures # no rollover when we add 1. self._rtcbuf[6] = (isecs + 1) % 60 rtc.datetime(self._rtcbuf) self._rtc_set = False # Could be an outage here, so PPS arrives many secs after last sentence # Is this right? Does PPS continue during outage? self._pps_cb(self, *self._pps_cb_args) # Called when base class updates the epoch_time. # Need local time for setting Pyboard RTC in interrupt context
Example #23
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def close(self): self._pps_pin.irq(None) # If update rate > 1Hz, when PPS edge occurs the last RMC message will have # a nonzero ms value. Need to set RTC to 1 sec after the last 1 second boundary
Example #24
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def setup(self, pps_pin, pps_cb, pps_cb_args): self._pps_pin = pps_pin self._pps_cb = pps_cb self._pps_cb_args = pps_cb_args self.msecs = None # Integer time in ms since midnight at last PPS self.t_ms = 0 # ms since midnight self.acquired = None # Value of ticks_us at edge of PPS self._rtc_set = False # Set RTC flag self._rtcbuf = [0]*8 # Buffer for RTC setting self._time = [0]*4 # get_t_split() time buffer. loop = asyncio.get_event_loop() loop.create_task(self._start())
Example #25
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _calculate(self, gps_start, gps_end, rtc_start, rtc_end): # Duration (μs) between PPS edges pps_delta = (gps_end - gps_start) # Duration (μs) between PPS edges as measured by RTC and corrected rtc_delta = (rtc_end - rtc_start) ppm = (1000000 * (rtc_delta - pps_delta)) / pps_delta # parts per million return int(-ppm/0.954) # Measure difference between RTC and GPS rate and return calibration factor # If 3 successive identical results are within 1 digit the outcome is considered # valid and the coro quits.
Example #26
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _await_pps(self): t0 = self.acquired while self.acquired == t0: # Busy-wait on PPS interrupt: not time-critical await asyncio.sleep_ms(0) # because acquisition time stored in ISR. gc.collect() # Time-critical code follows st = rtc.datetime()[7] while rtc.datetime()[7] == st: # Wait for RTC to change (4ms max) pass dt = utime.ticks_diff(utime.ticks_us(), self.acquired) trtc = self._get_rtc_usecs() - dt # Read RTC now and adjust for PPS edge tgps = 1000000 * (self.epoch_time + 3600*self.local_offset + 1) return trtc, tgps # Non-realtime calculation of calibration factor. times are in μs
Example #27
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def delta(self): if not on_pyboard: raise OSError('Only available on STM targets.') rtc_time, gps_time = await self._await_pps() # μs since Y2K at time of latest PPS return rtc_time - gps_time # Pause until PPS interrupt occurs. Then wait for an RTC subsecond change. # Read the RTC time in μs since Y2K and adjust to give the time the RTC # (notionally) would have read at the PPS leading edge.
Example #28
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _get_rtc_usecs(self): y, m, d, weekday, hrs, mins, secs, subsecs = rtc.datetime() tim = 1000000 * utime.mktime((y, m, d, hrs, mins, secs, weekday - 1, 0)) return tim + ((1000000 * (255 - subsecs)) >> 8) # Return no. of μs RTC leads GPS. Done by comparing times at the instant of # PPS leading edge.
Example #29
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def set_rtc(self): if not on_pyboard: raise OSError('Only available on STM targets.') self._rtc_set = True while self._rtc_set: await asyncio.sleep_ms(250) # Value of RTC time at current instant. This is a notional arbitrary # precision integer in μs since Y2K. Notional because RTC is set to # local time.
Example #30
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _isr(self, _): acquired = utime.ticks_us() # Save time of PPS # Time in last NMEA sentence was time of last PPS. # Reduce to integer secs since midnight local time. isecs = (self.epoch_time + int(3600*self.local_offset)) % 86400 # ms since midnight (28 bits). Add in any ms in RMC data msecs = isecs * 1000 + self.msecs # This PPS is presumed to be one update later msecs += self._update_ms if msecs >= 86400000: # Next PPS will deal with rollover return if self.t_ms == msecs: # No RMC message has arrived: nothing to do return self.t_ms = msecs # Current time in ms past midnight self.acquired = acquired # Set RTC if required and if last RMC indicated a 1 second boundary if self._rtc_set: # Time as int(seconds) in last NMEA sentence. Earlier test ensures # no rollover when we add 1. self._rtcbuf[6] = (isecs + 1) % 60 rtc.datetime(self._rtcbuf) self._rtc_set = False # Could be an outage here, so PPS arrives many secs after last sentence # Is this right? Does PPS continue during outage? self._pps_cb(self, *self._pps_cb_args) # Called when base class updates the epoch_time. # Need local time for setting Pyboard RTC in interrupt context