def esp_sleep(seconds): print("Going to sleep for " + str(seconds) + "seconds") rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) time.sleep(2) rtc.alarm(rtc.ALARM0, seconds * 1000) machine.deepsleep()
def deep_sleep(msecs): # configure RTC.ALARM0 to be able to wake the device rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=DEEPSLEEP) # set RTC.ALARM0 to fire after X milliseconds (waking the device) rtc.alarm(rtc.ALARM0, msecs) # put the device to sleep deepsleep()
def deep_sleep(delay=300000): ''' deep sleep function, default delay = 1000 * 60 * 5 = 300000 ms = 5 mins GPIO16 must be connected to RST (D0 to RST) ''' rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) myprint('[i] Entering deep sleep for {0:.2f} min ({1} ms).'.format(delay / 60 / 1000, delay)) rtc.alarm(rtc.ALARM0, delay) machine.deepsleep()
def dsleep(): #Configure RTC.ALARM0 to be able to wake the device rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) #Set RTC.ALARM0 to fire after 5 seconds (waking the device) rtc.alarm(rtc.ALARM0, 5000) #Go to sleep machine.deepsleep()
def hardreset(): # configure RTC.ALARM0 to be able to wake the device rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=DEEPSLEEP) # set RTC.ALARM0 to fire after 1000 ms (waking the device) rtc.alarm(rtc.ALARM0, 1000) # put the device to sleep deepsleep()
async def sleep(): """ pushes the device into a deep sleep mode """ from machine import RTC, DEEPSLEEP, deepsleep await asyncio.sleep(3) print('.... in deep sleep zzZz') # configure RTC.ALARM0 to be able to wake the device rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=DEEPSLEEP) # set RTC.ALARM0 to fire after 10 seconds (waking the device) rtc.alarm(rtc.ALARM0, 10000) # put the device to sleep deepsleep()
def deepsleep(): print('The device will now sleep.') rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) rtc.alarm(rtc.ALARM0, g_sleep_time * 1000) machine.deepsleep()
def _sleep(_): print('deepsleep starting for {} seconds'.format(DEEPSLEEP_TIME)) rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=DEEPSLEEP) rtc.alarm(rtc.ALARM0, DEEPSLEEP_TIME * 1000) deepsleep()
from machine import RTC from machine import LED rtc = RTC() #创建RTC对象 print(rtc.now()) #获取当前日期时间 rtc.alarm(time=10, repeat=True) #设置RTC 10秒警报, 並且重复设置 l = LED(1) #创建LED1为输出对象 irq_count = 0 def alarm_handler(t): #时钟警报回调函数 global irq_count if (irq_count % 2) == 0: l.on() else: l.off() irq_count += 1 rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler) #创建由系统时钟警报触发的中断对象
raise Exception('Board not supported!') def rtc_ticks_ms(rtc): timedate = rtc.now() return (timedate[5] * 1000) + (timedate[6] // 1000) rtc_irq_count = 0 def alarm_handler (rtc_o): global rtc_irq global rtc_irq_count if rtc_irq.flags() & RTC.ALARM0: rtc_irq_count += 1 rtc = RTC() rtc.alarm(time=500, repeat=True) rtc_irq = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler) # active mode time.sleep_ms(1000) rtc.alarm_cancel() print(rtc_irq_count == 2) rtc_irq_count = 0 rtc.alarm(time=200, repeat=True) time.sleep_ms(1000) rtc.alarm_cancel() print(rtc_irq_count == 5) rtc_irq_count = 0 rtc.alarm(time=100, repeat=True) time.sleep_ms(1000)
import bme280
mpu6050.MPU_Init(i2c, int(config['mpu6050_addr'])) setup_wifi(config['wifi']['ssid'], password=config['wifi']['password']) client = MQTTClient(config['mqtt']['client_id'], config['mqtt']['broker']) tilts = [] for _ in range(config['num_samples']): acc = mpu6050.read_accel_data(i2c, int(config['mpu6050_addr'])) temp = mpu6050.read_temp_data(i2c, int(config['mpu6050_addr'])) modulus = math.sqrt(sum([a * a for a in acc])) tilts.append(math.acos(acc[2] / modulus) * RAD_TO_DEG) time.sleep_ms(200) tilts.sort() if config['num_samples'] % 2 == 0: tilt = (tilts[config['num_samples'] // 2] + tilts[config['num_samples'] // 2 - 1]) / 2. else: tilt = tilts[config['num_samples'] // 2] client.connect() client.publish(config['mqtt']['topic'] + '/tilt', b'%.02f' % (tilt)) client.publish(config['mqtt']['topic'] + '/temperature', b'%.02f' % (temp)) client.disconnect() print('Tilt: %.2f Temp: %.2f C' % (tilt, temp)) rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=DEEPSLEEP) rtc.alarm(RTC.ALARM0, 1000 * config['sleep_time']) deepsleep()
timedate = rtc.now() return (timedate[5] * 1000) + (timedate[6] // 1000) rtc_irq_count = 0 def alarm_handler(rtc_o): global rtc_irq global rtc_irq_count if rtc_irq.flags() & RTC.ALARM0: rtc_irq_count += 1 rtc = RTC() rtc.alarm(time=500, repeat=True) rtc_irq = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler) # active mode time.sleep_ms(1000) rtc.alarm_cancel() print(rtc_irq_count == 2) rtc_irq_count = 0 rtc.alarm(time=200, repeat=True) time.sleep_ms(1000) rtc.alarm_cancel() print(rtc_irq_count == 5) rtc_irq_count = 0 rtc.alarm(time=100, repeat=True) time.sleep_ms(1000)
class Display(object): IMG_DIR = '/flash/imgs' def __init__(self, debug=False): self.cfg = None self.rtc = RTC() self.debug = debug self.battery = Battery() # use this pin for debug self.wifi_pin = Pin("GP24", mode=Pin.IN, pull=Pin.PULL_UP) # Empty WDT object self.wdt = None if not debug: if not self.wifi_pin(): self.wdt = WDT(timeout=20000) self.sd = None else: from machine import SD try: self.sd = SD() mount(self.sd, '/sd') self.logfile = open("/sd/display.log", "a") except OSError: self.sd = None self.logfile = None self.epd = EPD() self.log("Time left on the alarm: %dms" % self.rtc.alarm_left()) # Don't flash when we're awake outside of debug heartbeat(self.debug) def log(self, msg, end='\n'): time = "%d, %d, %d, %d, %d, %d" % self.rtc.now()[:-2] msg = time + ", " + msg if self.logfile: self.logfile.write(msg + end) print(msg, end=end) def feed_wdt(self): if self.wdt: self.wdt.feed() def connect_wifi(self): from network import WLAN if not self.cfg: raise ValueError("Can't initialise wifi, no config") self.log('Starting WLAN, attempting to connect to ' + ','.join(self.cfg.wifi.keys())) wlan = WLAN(0, WLAN.STA) wlan.ifconfig(config='dhcp') while not wlan.isconnected(): nets = wlan.scan() for network in nets: if network.ssid in self.cfg.wifi.keys(): self.log('Connecting to ' + network.ssid) self.feed_wdt() # just in case wlan.connect(ssid=network.ssid, auth=(network.sec, self.cfg.wifi[network.ssid])) while not wlan.isconnected(): idle() break self.feed_wdt() # just in case sleep_ms(2000) self.log('Connected as %s' % wlan.ifconfig()[0]) @staticmethod def reset_cause(): import machine val = machine.reset_cause() if val == machine.POWER_ON: return "power" elif val == machine.HARD_RESET: return "hard" elif val == machine.WDT_RESET: return "wdt" elif val == machine.DEEPSLEEP_RESET: return "sleep" elif val == machine.SOFT_RESET: return "soft" def set_alarm(self, now, json_metadata): import json json_dict = json.loads(json_metadata) # Now we know the time too self.rtc = RTC(datetime=now) list_int = json_dict["wakeup"][:6] time_str = ",".join([str(x) for x in list_int]) self.log("Setting alarm for " + time_str) self.rtc.alarm(time=tuple(list_int)) if self.rtc.alarm_left() == 0: self.log("Alarm failed, setting for +1 hour") self.rtc.alarm(time=3600000) del json def display_file_image(self, file_obj): towrite = 15016 max_chunk = 250 while towrite > 0: c = max_chunk if towrite > max_chunk else towrite buff = file_obj.read(c) self.epd.upload_image_data(buff, delay_us=2000) self.feed_wdt() towrite -= c self.epd.display_update() def display_no_config(self): self.log("Displaying no config msg") with open(Display.IMG_DIR + '/no_config.bin', 'rb') as pic: self.display_file_image(pic) def display_low_battery(self): self.log("Displaying low battery msg") with open(Display.IMG_DIR + '/low_battery.bin', 'rb') as pic: self.display_file_image(pic) def display_cannot_connect(self): self.log("Displaying no server comms msg") with open(Display.IMG_DIR + '/no_server.bin', 'rb') as pic: self.display_file_image(pic) def display_no_wifi(self): self.log("Displaying no wifi msg") with open(Display.IMG_DIR + '/no_wifi.bin', 'rb') as pic: self.display_file_image(pic) def check_battery_level(self): now_batt = 200 last_batt = self.battery.battery_raw() while now_batt > last_batt: sleep_ms(50) last_batt = now_batt self.feed_wdt() now_batt = self.battery.battery_raw() self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw())) if not self.battery.safe(): self.log("Battery voltage (%d) low! Turning off" % self.battery.battery_raw()) self.feed_wdt() self.display_low_battery() return False else: self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw())) return True def run_deepsleep(self): if not self.run(): # RTC wasn't set, try to sleep forever self.rtc.alarm(time=2000000000) # Set the wakeup (why do it earlier?) rtc_i = self.rtc.irq(trigger=RTC.ALARM0, wake=DEEPSLEEP) self.log("Going to sleep, waking in %dms" % self.rtc.alarm_left()) # Close files on the SD card if self.sd: self.logfile.close() self.logfile = None unmount('/sd') self.sd.deinit() # Turn the screen off self.epd.disable() if not self.wifi_pin(): # Basically turn off deepsleep() else: self.log("DEBUG MODE: Staying awake") pass # Do nothing, allow network connections in def run(self): woken = self.wifi_pin() self.epd.enable() if not self.check_battery_level(): return False try: self.epd.get_sensor_data() except ValueError: self.log("Can't communicate with display, flashing light and giving up") heartbeat(True) sleep_ms(15000) return True if self.rtc.alarm_left() > 0: self.log("Woken up but the timer is still running, refreshing screen only") self.epd.display_update() self.feed_wdt() return True try: self.cfg = Config.load(sd=self.sd) self.log("Loaded config") except (OSError, ValueError) as e: self.log("Failed to load config: " + str(e)) self.display_no_config() try: self.connect_wifi() except: pass # everything while True: sleep_ms(10) self.feed_wdt() self.feed_wdt() self.connect_wifi() content = b'' try: self.log("Connecting to server %s:%d" % (self.cfg.host, self.cfg.port)) c = Connect(self.cfg.host, self.cfg.port, debug=self.debug) self.feed_wdt() cause = Display.reset_cause() if woken: cause = "user" self.log("Reset cause: " + cause) if len(self.cfg.upload_path) > 0: temp = self.epd.get_sensor_data() # we read this already c.post(self.cfg.upload_path, battery=self.battery.value(), reset=cause, screen=temp) self.log("Fetching metadata from " + self.cfg.metadata_path) metadata = c.get_quick(self.cfg.metadata_path, max_length=1024, path_type='json') # This will set the time to GMT, not localtime self.set_alarm(c.last_fetch_time, metadata) self.feed_wdt() del metadata del self.battery self.log("Fetching image from " + self.cfg.image_path) self.epd.image_erase_frame_buffer() self.feed_wdt() length, socket = c.get_object(self.cfg.image_path) if length != 15016: raise ValueError("Wrong data size for image: %d" % length) self.feed_wdt() except (RuntimeError, ValueError, OSError) as e: self.log("Failed to get remote info: " + str(e)) self.display_cannot_connect() self.rtc.alarm(time=3600000) return True sleep_ms(1000) # How do we make the write to display more reliable? self.feed_wdt() self.log("Uploading to display") self.display_file_image(socket) c.get_object_done() # close off socket if self.cfg.src == "sd": # If we've got a working config from SD instead of flash self.log("Transferring working config") Config.transfer() self.log("SUCCESS") self.log("Finished. Mem free: %d" % gc.mem_free()) return True
# Create the sensor object using I2C sensor = ahtx0.AHT10(i2c) # configure pin to prevent deepsleep, must by connected to GND to stop deepsleep ds_pin = Pin(14, Pin.IN, Pin.PULL_UP) # configure RTC.ALARM0 to be able to wake the device rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=DEEPSLEEP) # check if the device woke from a deep sleep if reset_cause() == DEEPSLEEP_RESET: print('woke from a deep sleep') # set RTC.ALARM0 to fire after 10 seconds (waking the device) rtc.alarm(rtc.ALARM0, 10000) # connect to wifi wlan = network.WLAN(network.STA_IF) if not wlan.isconnected(): print("establishing wifi connection...") wlan.active(True) wlan.connect("SSID", "Password") while not wlan.isconnected(): pass print("wifi connected") print("establishing mqtt broker connection...") c = MQTTClient("umqtt_client", "hostname") c.connect() print("connected to mqtt broker")
from machine import RTC from machine import LED rtc = RTC(datetime=(2019, 4, 25, 9, 0, 0)) #创建RTC对象, 设定时间为2019/4/25 9:00:00 print(rtc.now()) #获取当前日期时间 rtc.alarm(time=(2019, 4, 25, 9, 1, 30), repeat=False) #设置RTC警报为2019/4/25 9:01:30 l = LED(1) #创建LED1为输出对象, def alarm_handler(t): l.on() #时钟警报触发时,P21输出为高 rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler) #创建由系统时钟警报触发的中断对象
set_and_print((2000, 1, 31, 0, 0, 0, 0, None)) set_and_print((2000, 12, 31, 0, 0, 0, 0, None)) set_and_print((2016, 12, 31, 0, 0, 0, 0, None)) set_and_print((2016, 12, 31, 0, 0, 0, 0, None)) set_and_print((2016, 12, 31, 1, 0, 0, 0, None)) set_and_print((2016, 12, 31, 12, 0, 0, 0, None)) set_and_print((2016, 12, 31, 13, 0, 0, 0, None)) set_and_print((2016, 12, 31, 23, 0, 0, 0, None)) set_and_print((2016, 12, 31, 23, 1, 0, 0, None)) set_and_print((2016, 12, 31, 23, 59, 0, 50, None)) set_and_print((2016, 12, 31, 23, 59, 1, 900, None)) set_and_print((2016, 12, 31, 23, 59, 59, 100, None)) set_and_print((2048, 12, 31, 23, 59, 59, 99999, None)) rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) rtc.alarm(0, 5000) rtc.alarm(time=2000) time.sleep_ms(1000) left = rtc.alarm_left() print(abs(left - 1000) <= 10) time.sleep_ms(1000) print(rtc.alarm_left() == 0) time.sleep_ms(100) print(rtc.alarm_left(0) == 0) rtc.alarm(time=1000, repeat=True) time.sleep_ms(1500) left = rtc.alarm_left() print(abs(left - 500) <= 15) rtc.init((2015, 8, 29, 9, 0, 0, 0, None))
webrepl.start() gc.collect() # This portion connects to the network on boot wlan = network.WLAN(network.STA_IF) # create station interface wlan.active(True) # activate the interface try: wlan.connect('WIFI', 'password') # connect to an AP except: sleep(60) rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=DEEPSLEEP) rtc.alarm(rtc.ALARM0, 540000) print('Network unavailable. Going to deepsleep ...') deepsleep() # put the device to sleep deepsleep() ap = network.WLAN(network.AP_IF) # Disables the AP ap.active(False) # Assign Pins trig = Pin(12, Pin.OUT) echo = Pin(15, Pin.IN) def distance(): trig.off() sleep_us(5)
# STOP irrigation TODO this code must be extra safe # toggle OFF pin for testing print("Stopping irrigaiton") irrgationStop() curr_tm = getDateTime() # save state to RTC memory print("Saving state") saveState(str(curr_tm)) # safety sleep to allow multitasking between ESP core and WiFI print("10 seconds sleep before DEEP SLEEP") time.sleep(10) # go to DEEP SLEEP # configure RTC.ALARM0 to be able to wake the device print("Configure trigger") rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) # set RTC.ALARM0 to fire after 10 seconds (waking the device) sleep_ms = DEEP_SLEEP_INTERVAL * 1000 print("set alarm") rtc.alarm(rtc.ALARM0, sleep_ms) # put the device to sleep print("going to sleep for: ", DEEP_SLEEP_INTERVAL, "seconds") machine.deepsleep() #LOG
set_and_print((2000, 1, 31, 0, 0, 0, 0, None)) set_and_print((2000, 12, 31, 0, 0, 0, 0, None)) set_and_print((2016, 12, 31, 0, 0, 0, 0, None)) set_and_print((2016, 12, 31, 0, 0, 0, 0, None)) set_and_print((2016, 12, 31, 1, 0, 0, 0, None)) set_and_print((2016, 12, 31, 12, 0, 0, 0, None)) set_and_print((2016, 12, 31, 13, 0, 0, 0, None)) set_and_print((2016, 12, 31, 23, 0, 0, 0, None)) set_and_print((2016, 12, 31, 23, 1, 0, 0, None)) set_and_print((2016, 12, 31, 23, 59, 0, 50, None)) set_and_print((2016, 12, 31, 23, 59, 1, 900, None)) set_and_print((2016, 12, 31, 23, 59, 59, 100, None)) set_and_print((2048, 12, 31, 23, 59, 59, 99999, None)) rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) rtc.alarm(0, 5000) rtc.alarm(time=2000) time.sleep_ms(1000) left = rtc.alarm_left() print(abs(left-1000) <= 10) time.sleep_ms(1000) print(rtc.alarm_left() == 0) time.sleep_ms(100) print(rtc.alarm_left(0) == 0) rtc.alarm(time=1000, repeat=True) time.sleep_ms(1500) left = rtc.alarm_left() print(abs(left-500) <= 15) rtc.init((2015, 8, 29, 9, 0, 0, 0, None))
justify_right(str(dht.temperature()) + ' / ' + str(temperature) + ' C', 10) show('text', 'P: ', 0, 20) justify_right(str(pressure) + ' hPa', 20) show('text', 'RH', 0, 30) justify_right(str(humidity) + ' %', 30) show('line', 0, 52, 128, 52, 1) justify_right(wifi.ifconfig()[0], 56) show('show') utime.sleep(2) if wifi.isconnected(): feed_data = [{'key': 'humidity', 'value': humidity}] if bme is not None: feed_data.append({'key': 'pressure', 'value': pressure}) feed_data.append({'key': 'temperature', 'value': dht.temperature()}) else: feed_data.append({'key': 'temperature', 'value': dht.temperature()}) if light_sensor is not None: feed_data.append({'key': 'luminance', 'value': luminance}) request = urequests.post( adafruit_url, json={'feeds': feed_data}, headers={'X-AIO-Key': 'b4a84d8373a447c1b9140167b3bb2f4d'}) rtc = RTC() rtc.irq(trigger=RTC.ALARM0, wake=DEEPSLEEP) rtc.alarm(RTC.ALARM0, 300000) deepsleep()
mqtt.connect() print("connected") return mqtt ###### MAIN ###### # Read sensors sensors = readSensors() # Send result via mqtt mqtt = connectMQTT() for sensor, data in sensors.items(): print("Sending: " + dumps(data)) mqtt.publish( config["mqtt"]["topics"] + "/" + config["hostname"] + "/" + sensor, dumps(data)) # Wait for message(s) to be published sleep(3) mqtt.disconnect() # Enter next cycle for 10 minutes deep sleep print("Going back to sleep...") rtc = RTC() rtc.irq(trigger=rtc.ALARM0, wake=DEEPSLEEP) rtc.alarm(rtc.ALARM0, 600000) deepsleep()