def cb(_): print('Deep sleep: %s sec' % config.BATT_LOW_SLEEP) sleep(2) state.stop() sleep(2) deepsleep(config.BATT_LOW_SLEEP * 1000000) sleep(2)
def _sleep(self): if locals().get('HOURLY_SLEEP_DEBUG'): print('Debug set, sleeping for 6 seconds instead of an hour') duration = 6 else: duration = 60 * 60 print('Sleeping for hour {} of {}'.format(self.iteration, self.hours)) esp.deepsleep(1000000 * duration)
def cb(_): t = config.ALARM_SLEEP if hub.water and hub.enable else config.NORMAL_SLEEP print('deepsleep', t) try: hub.stop() except: pass sleep(5) deepsleep(t * 1000000)
def deepsleep(): # import machine # rtc = machine.RTC() # rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) # machine.deepsleep() # new version: import esp esp.deepsleep(500) # possible to wake up after ... ms
def deepsleep(sleep_time=deepsleep_seconds): for x in range(0, 3): print("Deepsleep in " + str((10 - x)) + " Seconds") sleep(1) try: mqtt_c.disconnect() except: print("could not disconnect") sleep(1) esp.deepsleep(sleep_time * 1000000) sleep(1)
def overtime(t): #overtime, puts esp8266 to sleep print("overtime soon") sleep(1) for x in range(0, 10): print(str(10 - x) + " seconds left until overtime") sleep(1) try: pin15.low( ) #On Wio Node/Link pin15 defines power to the external ports except: print("pin15 not defined yet") esp.deepsleep(600 * 10**6)
def sleep(): if config['deepsleep'] and not client.repl: print('Entering deepsleep') client.disconnect() # give us some time to reprogram if(machine.reset_cause() != machine.DEEPSLEEP_RESET): for x in range(10): togleLed() time.sleep_ms(100) togleLed() time.sleep_ms(500) micro = 1000000 esp.deepsleep(config['interval_minutes'] * 60 * micro) time.sleep(1) else: for x in range(config['interval_minutes'] * 60): client.update() time.sleep(1)
def main(): topic = configuration.get('topic') submit_interval = configuration.get('submit_interval') exception_timeout = configuration.get('exception_reset_timeout') mqtt_server_ip = configuration.get('mqtt_server_ip') client_id = ubinascii.hexlify(machine.unique_id()) try: client = MQTTClient(client_id, mqtt_server_ip) client.connect() print('Connected to {}'.format(mqtt_server_ip)) temperature, humidity = sensor.measure() info = {'temperature': temperature, 'humidity': humidity} client.publish(topic, ujson.dumps(info)) client.disconnect() print('sleeping deeply for {} seconds'.format(submit_interval)) # deep sleep argument in microseconds esp.deepsleep(submit_interval * 1000000) except Exception as e: print(('Caught exception, {}' 'resetting in {} seconds...').format(e, exception_timeout)) time.sleep(exception_timeout) machine.reset()
def stop_after(delay=60, action="reset", wake_after=600): """Start a timer thread, which will restart/sleep the device after 'delay' secs. :param delay: Delay before restart/sleep. :param action: Reset or sleep the device. :param wake_after: If sleeping, how long until wake (in seconds). """ timer = Timer(-1) if action == "deepsleep": # lambda to handle mandatory callback arg (x) cb = lambda x: deepsleep(1000000 * (wake_after + delay)) else: cb = lambda x: reset() timer.init(mode=Timer.ONE_SHOT, period=1000 * delay, callback=cb)
def deep_sleep_esp(msecs): try: # configure RTC.ALARM0 to be able to wake the device timer = machine.Timer(-1) timer.init(period=15000, mode=machine.Timer.ONE_SHOT, callback=lambda t: esp.deepsleep(10000000)) # set RTC.ALARM0 to fire after X milliseconds (waking the device) rtc = machine.RTC() rtc.alarm(rtc.ALARM0, msecs) # put the device to sleep machine.deepsleep() except Exception as e: print(e)
def enter_deepsleep(seconds=0): if seconds == 0: esp.deepsleep() else: us = seconds * 1000000 esp.deepsleep(us)
from . import config state = {} print('Temp', '...') from .temp import Temp Temp(state) print(state) print('Net', '...') from .net import Net Net(state) print('deepsleep', config.FREQ, '...') ## https://docs.micropython.org/en/latest/library/esp.html#esp.deepsleep ## Note, GPIO pin 16 (or D0 on the Wemos D1 Mini) must be wired to the Reset pin. See README ## Note: ESP8266 only - use machine.deepsleep() on ESP32 ## https://docs.micropython.org/en/latest/esp8266/tutorial/powerctrl.html#deep-sleep-mode from esp import deepsleep deepsleep(config.FREQ * 1000000)
print("using DHCP...") ### Setup ADC to measure VCC if not adcmode.set_adc_mode(adcmode.ADC_MODE_VCC): print("ADC mdode changed in flash - restart needed") machine.reset() vcc = machine.ADC(1).read()/1024.0 while not sta_if.isconnected(): time.sleep(0.5) print("wifi connected: ", sta_if.ifconfig()) ### connect to MQTT CLIENT_ID = ubinascii.hexlify(machine.unique_id()) client = MQTTClient(CLIENT_ID, secrets.MQTT_SVR, user=secrets.MQTT_USER, password=secrets.MQTT_PWD ) client.connect() print("mqtt: connected") payload = secrets.MQTT_PAYLOAD.format(vcc) client.publish(secrets.MQTT_TOPIC, payload) print("mqtt: published %s: %s"%(secrets.MQTT_TOPIC, payload)) client.disconnect() print("mqtt: disconnected") except Exception as e: print( "FATAL: ", type(e) ) print( " ", repr(e) ) time.sleep(0.1) # without this, deepsleep doesn't work well esp.deepsleep(0)
import network import time #access the wifi and disable ap = network.WLAN(network.AP_IF) ap.active(False) sta_if = network.WLAN(network.STA_IF) sta_if.active(False) from esp import deepsleep from machine import reset_cause, DEEPSLEEP_RESET #turn off the wifi modem for a ~30ma drop in consumption if not reset_cause() == DEEPSLEEP_RESET: # call 'system_deep_sleep_set_option' with value 4 and go to sleep for 1 uS deepsleep(1, 4) else: time.sleep(6) import gc gc.collect() import sx127x gc.collect() import test gc.collect() test.main()
import utils import dht import machine import esp import time DHT_PIN = 14 dht22 = dht.DHT22(machine.Pin(DHT_PIN)) time.sleep(5) try: dht22.measure() aws_config = utils.get_config('/config/aws_info.json') result = utils.iot_put(aws_config, { 'temperature': dht22.temperature(), 'humidity': dht22.humidity() }) print("iot put result: {}".format(result)) except Exception as e: print("exception {}".format(e)) # 30 minutes esp.deepsleep(30 * 60 * 1000000)
def main(): global device device = next(chromecast) enc = Encoder(12, 13, clicks=2, reverse=False) np = volume.NeoPixelRing(4, device, machine.Pin(15), 16) button = machine.Pin(5, machine.Pin.IN) cast = connect2device(np) current_vol = cast.get_volume print('Connected to:', cast_name[device], device, 'current vol:', current_vol) enc.set_val(current_vol) last_enc_val = current_vol last_change_tick = time.ticks_ms() np.change_device(device, current_vol) while True: val = enc.value if last_enc_val != val: print(val) np.set_vol(val) last_enc_val = val last_change_tick = time.ticks_ms() #CHANGING VOLUME if (time.ticks_diff(time.ticks_ms(), last_change_tick) > 200) and (last_enc_val != current_vol): cast.set_volume(val) current_vol = cast.get_volume print('current volume:', current_vol) #SLEEP AFTER DELAY if (time.ticks_diff(time.ticks_ms(), last_change_tick) > 10000): #10 sec cast.disconnect() np.turn_off() print("SLEEP") esp.deepsleep() #CHANGING CHROMECAST WITH ENCODER BUTTON if button.value(): print('BUTTON PRESSED') b_start = time.ticks_ms() while button.value(): if (time.ticks_diff(time.ticks_ms(), b_start) > 2000): print('STOPPING PLAYBACK') np.stop() cast.stop_playback() time.sleep_ms(1500) np.set_vol(current_vol) last_change_tick = time.ticks_ms() break if time.ticks_diff(time.ticks_ms(), b_start) < 2000: cast.disconnect() prev_device = device device = next(chromecast) if device is not prev_device: cast = connect2device(np) current_vol = cast.get_volume enc.set_val(current_vol) np.change_device(device, current_vol) print('switched to:', cast_name[device], device, 'current vol:', current_vol) last_change_tick = time.ticks_ms() time.sleep_ms(100)
# Be sure to connect GPIO16 (D0) to RST or this won't work! import esp seconds = 10 # Put machine to sleep - wake = usecs esp.deepsleep(seconds * 1000000) # Optionally add the following to boot.py for sleep detection if machine.reset_cause() == machine.DEEPSLEEP_RESET: print('woke from a deep sleep') else: print('power on or hard reset')
gc.collect() if debugging: print(gc.mem_free()) # Output data to Arduino print("BEGIN SEND") uart = UART(1, 9600) # TX: GPIO2=D4, RX: none? (GPIO is also LED!) time.sleep(0.1) uart.write('{') uart.write('\n') for dirs in out: for deps in dirs: uart.write("{} \n".format(deps)) time.sleep(0.05) # give Arduino time to read the buffer uart.write("}") uart.write('\n') uart.write('\n') print("END SEND") print("") for dirs in out: for deps in dirs: print("{}\t".format(deps), end="") # print ("{:>4} \t".format(deps), end="") print("") print("") if debugging == False: w.wlan.active(False) print("Good night!") esp.deepsleep()
import esp, sys #_max_int = sys.maxsize esp.deepsleep(time=10000000) #sleep 10 seconds
import ambient import esp ssid = "ess-id" password = "******" i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4)) if (i2c.scan()[0] == 0x76): bme = bme280.BME280(i2c=i2c) am = ambient.Ambient(ch - id, 'write-key') station = network.WLAN(network.STA_IF) station.active(True) station.connect(ssid, password) while station.isconnected() == False: pass print(station.ifconfig()) print(bme.values) data = bme.read_compensated_data() r = am.send({ 'd1': data[0] / 100.0, 'd2': data[2] / 1024.0, 'd3': data[1] / 25600.0 }) print(r.status_code) r.close() esp.deepsleep(600 * 1000000) else: print('BME280 error!')
def deepsleep(self): self.timer.init( mode=machine.Timer.ONE_SHOT, period=1000 * self.delay, callback=lambda cb: deepsleep(1000000 * (self.wake_after + self.delay)))
print('network config:', wlan.ifconfig()) def measure_dht(): results = [] for one in range(3): time.sleep(2) dht11.measure() results.append(dht11.humidity()) print(results) return max(results) print('measuring...') roms = ds.scan() ds.convert_temp() dht_hum = measure_dht() ds18_temp = ds.read_temp(roms[0]) print('t:', ds18_temp, 'h:', dht_hum) do_connect() http_get( 'http://api.thingspeak.com/update?api_key=RNZ28OEQAELE4ML9&field1={}&field2={}' .format(ds18_temp, dht_hum)) print('GC alloc:{} free:{}'.format(gc.mem_alloc(), gc.mem_free())) gc.collect() esp.deepsleep(1000000 * 60 * 3)
import sds011 import machine import esp import utime as time if machine.reset_cause() == machine.DEEPSLEEP_RESET: print('Woke from a deep sleep') READ_SECONDS = 20 SLEEP_SECONDS = 60 DUTYCYCLE_REST_MINS = 0 # sds011.set_dutycycle(DUTYCYCLE_REST_MINS) sds011.wake() sds011.read(READ_SECONDS) sds011.sleep() esp.deepsleep(SLEEP_SECONDS * 1000000)
############################################################################### def rm_tweet_txt(): import os os.remove('tweet.txt') start_network() wait_network_up() try: f = open('tweet.txt', 'r') str = f.read(4096) f.close() import usocket import ussl s=usocket.socket() addr = usocket.getaddrinfo("api.twitter.com", 443)[0][-1] s.connect(addr) s=ussl.wrap_socket(s) print(s) s.write(str) print(s.read(4096)) s.close() rm_tweet_txt() except: import tweet import esp esp.deepsleep(1)
from umqtt.robust import MQTTClient import time import network from hx711 import HX711 from config import Config conf = Config()[__name__] # Enable the HX711 (64x amp, data=4, sck=5 (d2, d1) freq(160000000) scale = HX711(4, 5, channel=HX711.CHANNEL_A_64) scale.power_on() weight = scale.read() scale.power_off() # Wait for network up before proceeding wlan = network.WLAN(network.STA_IF) while not wlan.isconnected(): time.sleep_ms(10) client = MQTTClient(**conf) client.connect(clean_session=False) client.publish("{}/{}/{}".format(conf["client_id"], "sensor", "hx711"), str(weight), qos=1) # Uncomment this to enable deep sleeping deepsleep(600 * 1000000)