Python machine.RTC Examples
The following are 30
code examples of machine.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
machine
, or try the search function
.
Example #1
Source File: util_old.py From esp8266 with BSD 2-Clause "Simplified" License | 6 votes |
def deep_sleep(secs) : import machine # configure RTC.ALARM0 to be able to wake the device rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) # set RTC.ALARM0 to fire after 10 seconds (waking the device) rtc.alarm(rtc.ALARM0, secs) # put the device to sleep machine.deepsleep()
Example #2
Source File: main.py From iot-core-micropython with Apache License 2.0 | 6 votes |
def set_time(): ntptime.settime() tm = utime.localtime() tm = tm[0:3] + (0,) + tm[3:6] + (0,) machine.RTC().datetime(tm) print('current time: {}'.format(utime.localtime()))
Example #3
Source File: ds3231.py From upython-aq-monitor with MIT License | 6 votes |
def get_time(self, set_rtc = False): if set_rtc: data = self.await_transition() # For accuracy set RTC immediately after a seconds transition else: self.ds3231.readfrom_mem_into(DS3231_I2C_ADDR, 0, self.timebuf) data = self.timebuf ss = bcd2dec(data[0]) mm = bcd2dec(data[1]) if data[2] & 0x40: hh = bcd2dec(data[2] & 0x1f) if data[2] & 0x20: hh += 12 else: hh = bcd2dec(data[2]) wday = data[3] DD = bcd2dec(data[4]) MM = bcd2dec(data[5] & 0x1f) YY = bcd2dec(data[6]) if data[5] & 0x80: YY += 2000 else: YY += 1900 if set_rtc: rtc.init((YY, MM, DD, hh, mm, ss, 0)) return (YY, MM, DD, hh, mm, ss, 0, 0) # Time from DS3231 in time.time() format (less yday)
Example #4
Source File: ds3231_pb.py From micropython-samples with MIT License | 6 votes |
def _getcal_d(self, minutes, cal, verbose): verbose and print('Pyboard D. Waiting {} minutes for calibration factor.'.format(minutes)) rtc.calibration(cal) # Clear existing cal self.save_time() # Set DS3231 from RTC self.await_transition() # Wait for DS3231 to change: on a 1 second boundary t = rtc.datetime() # Get RTC time # Time of DS3231 transition measured by RTC in μs since start of day rtc_start_us = get_us(t) dsstart = utime.mktime(self.convert()) # DS start time in secs utime.sleep(minutes * 60) self.await_transition() # Wait for DS second boundary t = rtc.datetime() # Time of DS3231 transition measured by RTC in μs since start of day rtc_end_us = get_us(t) dsend = utime.mktime(self.convert()) # DS end time in secs if rtc_end_us < rtc_start_us: # It's run past midnight. Assumption: run time < 1 day! rtc_end_us += 24 * 3_600_000_000 dsdelta = (dsend - dsstart) * 1_000_000 # Duration (μs) between DS3231 edges as measured by DS3231 rtcdelta = rtc_end_us - rtc_start_us # Duration (μs) between DS edges as measured by RTC ppm = (1_000_000 * (rtcdelta - dsdelta)) / dsdelta if cal: # We've already calibrated. Just report results. verbose and print('Error {:4.1f}ppm {:4.1f}mins/year.'.format(ppm, ppm * 1.903)) return 0 cal = int(-ppm / 0.954) verbose and print('Error {:4.1f}ppm {:4.1f}mins/year. Cal factor {}'.format(ppm, ppm * 1.903, cal)) return cal
Example #5
Source File: ds3231_pb.py From micropython-samples with MIT License | 6 votes |
def await_transition(self): # Wait until DS3231 seconds value changes self.ds3231.readfrom_mem_into(DS3231_I2C_ADDR, 0, self.timebuf) ss = self.timebuf[0] while ss == self.timebuf[0]: self.ds3231.readfrom_mem_into(DS3231_I2C_ADDR, 0, self.timebuf) return self.timebuf # Get calibration factor for Pyboard RTC. Note that the DS3231 doesn't have millisecond resolution so we # wait for a seconds transition to emulate it. # This function returns the required calibration factor for the RTC (approximately the no. of ppm the # RTC lags the DS3231). # Delay(min) Outcome (successive runs). Note 1min/yr ~= 2ppm # 5 173 169 173 173 173 # 10 171 173 171 # 20 172 172 174 # 40 173 172 173 Mean: 172.3 # Note calibration factor is not saved on power down unless an RTC backup battery is used. An option is # to store the calibration factor on disk and issue rtc.calibration(factor) on boot.
Example #6
Source File: watchdog.py From pysmartnode with MIT License | 5 votes |
def __init__(self, id=0, timeout=120, use_rtc_memory=True): self._timeout = timeout / 10 self._counter = 0 self._timer = machine.Timer(id) self._use_rtc_memory = use_rtc_memory self._has_filesystem = False self.init() asyncio.get_event_loop().create_task(self._resetCounter()) """ Done in pysmartnode.main if use_rtc_memory and platform == "esp8266": rtc = machine.RTC() if rtc.memory() == b"WDT reset": logging.getLogger("WDT").critical("Reset reason: Watchdog") rtc.memory(b"") elif sys_vars.hasFilesystem(): self._has_filesystem = True try: with open("reset_reason.txt", "r") as f: if f.read() == "True": logging.getLogger("WDT").warn("Reset reason: Watchdog") except Exception as e: print(e) # file probably just does not exist try: os.remove("reset_reason.txt") except Exception as e: logging.getLogger("WDT").error("Error saving to file: {!s}".format(e)) """
Example #7
Source File: ush.py From esp8266 with BSD 2-Clause "Simplified" License | 5 votes |
def set_datetime(secs) : import utime import machine tm = utime.localtime(secs) tm = tm[0:3] + (0,) + tm[3:6] + (0,) machine.RTC().datetime(tm)
Example #8
Source File: ush.py From esp8266 with BSD 2-Clause "Simplified" License | 5 votes |
def set_datetime(secs): import utime import machine tm = utime.localtime(secs) tm = tm[0:3] + (0,) + tm[3:6] + (0,) machine.RTC().datetime(tm)
Example #9
Source File: wifi_esp32.py From pysmartnode with MIT License | 5 votes |
def _sync(): s = 1 while True: print("Synchronize time from NTP server ...") try: ntptime.settime() gc.collect() tm = time.localtime() hour = tm[3] + config.RTC_TIMEZONE_OFFSET day = tm[2] if hour > 24: hour -= 24 day += 1 elif hour < 0: hour += 24 day -= 1 tm = tm[0:2] + (day,) + (0,) + (hour,) + tm[4:6] + (0,) machine.RTC().datetime(tm) print("Set time to", time.localtime()) s = 1 await asyncio.sleep(18000) # every 5h except Exception as e: await logging.getLogger("wifi").asyncLog("error", "Error syncing time: {!s}, retry in {!s}s".format( e, s)) await asyncio.sleep(s) s += 5 # should prevent crashes because previous request was not finished and # sockets still open (Errno 98 EADDRINUSE). Got killed by WDT after a few minutes.
Example #10
Source File: wifi_esp8266.py From pysmartnode with MIT License | 5 votes |
def _sync(): s = 1 while True: print("Synchronize time from NTP server ...") try: ntptime.settime() gc.collect() tm = time.localtime() hour = tm[3] + config.RTC_TIMEZONE_OFFSET day = tm[2] if hour > 24: hour -= 24 day += 1 elif hour < 0: hour += 24 day -= 1 tm = tm[0:2] + (day,) + (0,) + (hour,) + tm[4:6] + (0,) machine.RTC().datetime(tm) print("Set time to", time.localtime()) s = 1 await asyncio.sleep(18000) # every 5h except Exception as e: await logging.getLogger("wifi").asyncLog("error", "Error syncing time: {!s}, retry in {!s}s".format( e, s)) await asyncio.sleep(s) s += 5 # should prevent crashes because previous request was not finished and # sockets still open (Errno 98 EADDRINUSE). Got killed by WDT after a few minutes.
Example #11
Source File: deepsleep.py From pysmartnode with MIT License | 5 votes |
def deepsleep(sleeping_time, wait_before_sleep=None, event=None): if wait_before_sleep is not None: await asyncio.sleep(wait_before_sleep) if event is not None: await event if platform == "esp32_LoBo": machine.deepsleep(int(sleeping_time * 1000)) else: rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) rtc.alarm(rtc.ALARM0, int(sleeping_time * 1000)) machine.deepsleep()
Example #12
Source File: device.py From terkin-datalogger with GNU Affero General Public License v3.0 | 5 votes |
def start_rtc(self): """ The RTC is used to keep track of the date and time. Syncs RTC with a NTP server. """ # https://docs.pycom.io/firmwareapi/pycom/machine/rtc.html # https://medium.com/@chrismisztur/pycom-uasyncio-installation-94931fc71283 import time from machine import RTC self.rtc = RTC() # TODO: Use values from configuration settings here. self.rtc.ntp_sync("pool.ntp.org", 360) while not self.rtc.synced(): time.sleep_ms(50) log.info('RTC: %s', self.rtc.now())
Example #13
Source File: watchdog.py From pysmartnode with MIT License | 5 votes |
def _wdt(self, t): self._counter += self._timeout if self._counter >= self._timeout * 10: if self._use_rtc_memory and platform == "esp8266": rtc = machine.RTC() rtc.memory(b"WDT reset") elif self._has_filesystem: try: with open("reset_reason.txt", "w") as f: f.write("WDT reset") except Exception as e: print("Error saving to file: {!s}".format(e)) machine.reset()
Example #14
Source File: Board.py From illuminOS with MIT License | 5 votes |
def sleep(self, milliseconds): # To be able to use this fea import machine # configure RTC.ALARM0 to be able to wake the device rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) # set RTC.ALARM0 to fire after some milliseconds rtc.alarm(rtc.ALARM0, milliseconds) # put the device to sleep machine.deepsleep()
Example #15
Source File: connect.py From webthing-upy with MIT License | 5 votes |
def start_ntp(): print('Syncing to NTP...') rtc = machine.RTC() rtc.ntp_sync(server='pool.ntp.org') if not rtc.synced(): print(' waiting for time sync...', end='') time.sleep(0.5) while not rtc.synced(): print('.', end='') time.sleep(0.5) print('') print('Time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
Example #16
Source File: device.py From microhomie with MIT License | 5 votes |
def run_forever(self): if RTC().memory() == b"webrepl": RTC().memory(b"") else: loop = get_event_loop() loop.run_until_complete(self.run())
Example #17
Source File: device.py From microhomie with MIT License | 5 votes |
def reset(self, reason): if reason != "reset": RTC().memory(reason) await self.publish(DEVICE_STATE, reason) await self.mqtt.disconnect() await sleep_ms(500) reset()
Example #18
Source File: inisetup.py From microhomie with MIT License | 5 votes |
def setup(): check_bootsec() print("Performing initial setup") wifi() uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) uos.mount(vfs, '/') with open("boot.py", "w") as f: f.write("""\ # This file is executed on every boot (including wake-boot from deepsleep) import esp esp.osdebug(None) #import uos, machine #uos.dupterm(None, 1) # disable REPL on UART(0) import gc from machine import RTC try: if RTC().memory() == b"webrepl": raise import main import settings from homie.utils import disable_ap disable_ap() except Exception: import webrepl from homie.utils import enable_ap enable_ap() webrepl.start(password="uhomie") gc.collect() """) return vfs
Example #19
Source File: ds3231_sensor.py From terkin-datalogger with GNU Affero General Public License v3.0 | 5 votes |
def start(self): """ Getting the bus """ if self.bus is None: raise KeyError("Bus missing for DS3231") # Initialize the hardware driver. try: self.driver = DS3231(i2c=self.bus.adapter) return True except Exception as ex: log.exc(ex, 'DS3231 hardware driver failed') # set date/time of RTC self.set_time()
Example #20
Source File: ds3231_sensor.py From terkin-datalogger with GNU Affero General Public License v3.0 | 5 votes |
def set_time(self): """ set the system time to RTC time """ rtc = RTC() [year,month,day,dotw,hour,minute,second] = self.driver.getDateTime() # get the date/time from the DS3231 if year > 2019: # check valid data rtc.init((year,month,day,dotw,hour,minute,second,0)) # set date/time log.debug("Time set: {}".format(rtc.datetime())) else: log.warning("DS3231 date/time not set, not setting RTC")
Example #21
Source File: util.py From developer-badge-2018-apps with Apache License 2.0 | 5 votes |
def run(appname='home'): rtc = machine.RTC() rtc.memory(appname) print('Restrt to run app {}'.format(appname)) restart()
Example #22
Source File: ds3231.py From upython-aq-monitor with MIT License | 5 votes |
def delta(self): # Return no. of mS RTC leads DS3231 self.await_transition() rtc_ms = now() t_ds3231 = utime.mktime(self.get_time()) # To second precision, still in same sec as transition return rtc_ms - 1000 * t_ds3231
Example #23
Source File: ntptime.py From micropy-cli with MIT License | 5 votes |
def settime(): t = time() import machine import utime tm = utime.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (0,) machine.RTC().datetime(tm) print(utime.localtime())
Example #24
Source File: ntptime.py From micropy-cli with MIT License | 5 votes |
def settime(): t = time() import machine import utime tm = utime.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (0,) machine.RTC().datetime(tm) print(utime.localtime())
Example #25
Source File: ntptime.py From micropy-cli with MIT License | 5 votes |
def settime(): t = time() import machine import utime tm = utime.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (0,) machine.RTC().datetime(tm) print(utime.localtime())
Example #26
Source File: ntptime.py From micropy-cli with MIT License | 5 votes |
def settime(): t = time() import machine import utime tm = utime.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (0,) machine.RTC().datetime(tm) print(utime.localtime())
Example #27
Source File: main.py From rshell with MIT License | 5 votes |
def set_time(rtc_time): rtc = None try: # Pyboard (pyboard doesn't have machine.RTC()). # The pyb.RTC.datetime function takes the arguments in the order: # (year, month, day, weekday, hour, minute, second, subseconds) # http://docs.micropython.org/en/latest/library/pyb.RTC.html#pyb.RTC.datetime import pyb rtc = pyb.RTC() rtc.datetime(rtc_time) except: try: import pycom # PyCom's machine.RTC takes its arguments in a slightly different order # than the official machine.RTC. # (year, month, day, hour, minute, second[, microsecond[, tzinfo]]) # https://docs.pycom.io/firmwareapi/pycom/machine/rtc/#rtc-init-datetime-none-source-rtc-internal-rc rtc_time2 = (rtc_time[0], rtc_time[1], rtc_time[2], rtc_time[4], rtc_time[5], rtc_time[6]) import machine rtc = machine.RTC() rtc.init(rtc_time2) except: try: # The machine.RTC documentation was incorrect and doesn't agree with the code, so no link # is presented here. The order of the arguments is the same as the pyboard. import machine rtc = machine.RTC() try: # ESP8266 uses rtc.datetime() rather than rtc.init() rtc.datetime(rtc_time) except: # ESP32 (at least Loboris port) uses rtc.init() rtc.init(rtc_time) except: pass # 0x0D's sent from the host get transformed into 0x0A's, and 0x0A sent to the # host get converted into 0x0D0A when using sys.stdin. sys.tsin.buffer does # no transformations, so if that's available, we use it, otherwise we need # to use hexlify in order to get unaltered data.
Example #28
Source File: ds3231_port.py From micropython-samples with MIT License | 5 votes |
def get_time(self, set_rtc=False): if set_rtc: self.await_transition() # For accuracy set RTC immediately after a seconds transition else: self.ds3231.readfrom_mem_into(DS3231_I2C_ADDR, 0, self.timebuf) # don't wait return self.convert(set_rtc)
Example #29
Source File: ds3231_pb.py From micropython-samples with MIT License | 5 votes |
def get_time(self, set_rtc=False): if set_rtc: self.await_transition() # For accuracy set RTC immediately after a seconds transition else: self.ds3231.readfrom_mem_into(DS3231_I2C_ADDR, 0, self.timebuf) # don't wait return self.convert(set_rtc)
Example #30
Source File: helpers.py From upython-aq-monitor with MIT License | 5 votes |
def setup_rtc(): rtc = machine.RTC() rtc.ntp_sync("pool.ntp.org") while not rtc.synced(): utime.sleep_ms(100) utime.timezone(3600)