def run(): """Main entry point to execute this program.""" if _isFirstRun(): _setRunsToCondition(CONDITIONING_RUNS) ccs = ccs811.CCS811(i2c, mode=ccs811.CCS811.DRIVE_MODE_60SEC) t, p, h = bme.read_data() # Full update of Waveshare on power on scr.update(t, h, None, None, bat.volts(), True) else: ccs = ccs811.CCS811(i2c, mode=None) _addRun() try: ccs.read() t, p, h = bme.read_data() ccs.put_envdata(t, h) if _isConditioned(): scr.update(t, h, ccs.eco2, ccs.tvoc, bat.volts()) else: scr.update(t, h, None, None, bat.volts()) print('eCO2: %dppm, TVOC: %dppb, %.1fC, %.1f%%RH' % (ccs.eco2, ccs.tvoc, t, h)) except OSError as e: print(e) _flashled() scr.sleep() esp32.wake_on_ext0(pin=config.int, level=0) machine.deepsleep()
def standby(self, duration=None): #self.slp.init(Pin.PULL_HOLD) #duration should be in seconds #level parameter can be: esp32.WAKEUP_ANY_HIGH or esp32.WAKEUP_ALL_LOW esp32.wake_on_ext0(pin=self.manual_open, level=esp32.WAKEUP_ALL_LOW) # Couldnt get ext1 with two wakeup switches to work. leave it here for knowledge... esp32.wake_on_ext1(pins=[self.manual_close], level=esp32.WAKEUP_ALL_LOW) #esp32.wake_on_ext1(pins = [self.manual_open, self.manual_close], level = esp32.WAKEUP_ALL_LOW) ### 1000 * 60 * 10 = 10m in milliseconds if duration: print( 'Going to sleep in 30s in case there are any pending threads...' ) sleep(30) print('Going to sleep now...') sleepytime = duration * 1000 deepsleep(sleepytime) else: # no duration specified, go into deepsleep indefinitely print('Going to sleep now...') deepsleep()
def powerdown(t=5): #turn off led strip badge.led_power.off() wake_on_ext0(pin=badge.button_mid, level=WAKEUP_ALL_LOW) #set esp to sleep deepsleep(1000 * 60 * t)
def sleepuntilnextsalat(raise_exceptions=True): """ returns idx when next salat time arrives """ try: if time.time() < 100000: #Still in year 2000 ! try: ntpsync() except: pass sidx, stime = sdb.findnextsalat(1) salm = sdb.getsalarmdelay(sidx) delta = -1 if salm != None: almtm = stime - (60 * salm) delta = almtm - time.mktime(localtime()) if delta > 0: print("Next salat alarm in %d seconds" % delta) if delta <= 0: delta = stime - time.mktime(localtime()) print("Next salat %s in %d seconds" % (SALATS[sidx], delta)) # Setup wakeup button if delta > 24 * 3600: delta = 24 * 3600 esp32.wake_on_ext0(wbutton, esp32.WAKEUP_ALL_LOW) player.sleep() machine.deepsleep(delta * 1000) except Exception as err: led.value(1) play_tone(100, 5000) with open('exception.log', 'w') as log: sys.print_exception(err, log) sys.print_exception(err) if raise_exceptions: raise
def pin_sleep(p): print("Going to sleep (pin press).") # Reconfigure pin as wakeup pin esp32.wake_on_ext0(pin=wakeSleepPin, level=esp32.WAKEUP_ANY_HIGH) # Wait half a second for button debounce time.sleep_ms(500) machine.deepsleep()
def deepsleep(): import esp32 esp32.wake_on_ext0(pin=touch, level=esp32.WAKEUP_ANY_HIGH) # for deepsleep testing with the breakout # esp32.wake_on_ext1(pins=(Pin(14, Pin.IN, Pin.PULL_DOWN), touch), level=esp32.WAKEUP_ANY_HIGH) deinit_hw_for_deepsleep() print("Going to sleep") machine.deepsleep()
def goSleepBoi(): wakePin = Pin(37, Pin.IN, Pin.PULL_DOWN) esp32.wake_on_ext0(wakePin, esp32.WAKEUP_ALL_LOW) print("Going to sleep in 3s") sleep(3) print("Going to sleep") turnOffScreen() deepsleep()
def go_to_sleep(): wake1 = Pin(SLEEP_PIN, Pin.IN, Pin.PULL_DOWN) esp32.wake_on_ext0( pin=wake1, level=esp32.WAKEUP_ANY_HIGH ) #level parameter can be: esp32.WAKEUP_ANY_HIGH or esp32.WAKEUP_ALL_LOW print('Im awake. Going to sleep in 1 seconds') sleep_ms(1000) print('Going to sleep now') machine.deepsleep()
def powerdown(caller=None): print("going to sleep") #turn off led strip badge.led_power.off() wake_on_ext0(pin=badge.button_mid, level=WAKEUP_ALL_LOW) #set esp to sleep deepsleep()
def setPinWakeUp(): """ Configure the wake up gpio on high level. For ESP32CAM, the GPIO 13 is used to detect the state of PIR detector. """ Battery.init() try: wake1 = machine.Pin(Battery.config.wakeUpGpio, mode=machine.Pin.IN) esp32.wake_on_ext0(pin=wake1, level=esp32.WAKEUP_ANY_HIGH) return True except Exception as err: print("Cannot set wake up") return False
def run(): """Main entry point to execute this program.""" try: bme = bme280.BME280(i2c=_i2c, mode=bme280.BME280_OSAMPLE_4) scr = screen.Screen(config) if _delete_ccs811_baseline_requested(): _baseline.delete() if _is_first_run(): # 20 runs (minutes), p9 of datasheet _set_runs_to_condition(20) ccs = ccs811.CCS811(_i2c, mode=ccs811.CCS811.DRIVE_MODE_60SEC) t, p, h = bme.read_data() # Full update of Waveshare on power on scr.update(t, h, None, None, _bat.volts(), False, True) else: ccs = ccs811.CCS811(_i2c, mode=None) _add_run() ccs.read() t, p, h = bme.read_data() ccs.put_envdata(t, h) if _ccs811_is_conditioned(): # Stored baseline should only be loaded after conditioning if not _ccs811_baseline_is_loaded() and _baseline.exists(): baseline = _baseline.retrieve() ccs.put_baseline(baseline) _set_ccs811_baseline_loaded() scr.update(t, h, None, None, _bat.volts()) print('ccs811 baseline %d loaded' % baseline) else: scr.update(t, h, ccs.eco2, ccs.tvoc, _bat.volts(), _ccs811_baseline_is_loaded()) if _new_ccs811_baseline_requested(): baseline = ccs.get_baseline() _baseline.store(baseline) print('ccs811 baseline %d stored' % baseline) else: scr.update(t, h, None, None, _bat.volts()) print('eCO2: %dppm, TVOC: %dppb, %.1fC, %.1f%%RH, baseline: %r' % (ccs.eco2, ccs.tvoc, t, h, _ccs811_baseline_is_loaded())) scr.sleep() _flash_led() except Exception as e: _flash_led(3) print(e) esp32.wake_on_ext0(pin=config.int, level=0) machine.deepsleep()
def __init__(self, tact_sw_pin_nr, timer_nrs, callbacks, hold_times_ms, rest_time_ms, wake_on_press=False): """ :param tact_sw_pin_nr: Tactile switch pin number. :param timer_nrs: Timer numbers used for debounce and hold/rest respectively. :param callbacks: Callbacks tuple, must contain 2 callbacks. :param hold_times_ms: Hold times (ms) tuple. If no hold times are used pass (0, ). :param rest_time_ms: Time it takes to reset the press count in ms. :param wake_on_press: The tactile switch is configured as a wake-up source if True. Default is False. """ if len(timer_nrs) < TactSwitch.NUM_TIMERS: raise ValueError if len(callbacks) < TactSwitch.NUM_CALLBACKS: raise ValueError TactSwitch.UserCallbacks = callbacks TactSwitch.PressTimer = Timer(timer_nrs[TactSwitch.TIMER_HOLD_REST]) if hold_times_ms[0] > 0: TactSwitch.HoldCallback = TactSwitch._HoldCallback TactSwitch.HoldTimes = hold_times_ms TactSwitch.RestCallback = TactSwitch._RestCallback TactSwitch.RestTime = rest_time_ms TactSwitch.DebounceTimer = Timer(timer_nrs[TactSwitch.TIMER_DEBOUNCE]) TactSwitch.DebounceTimerCallback = TactSwitch._DebounceTimerCallback if wake_on_press is False: wake_param = None else: wake_param = machine.DEEPSLEEP TactSwitch.TactSwPin = Pin(tact_sw_pin_nr, mode=Pin.IN) TactSwitch.TactSwPin.irq(trigger=(Pin.IRQ_RISING | Pin.IRQ_FALLING), handler=self._IrqHandlerTactSwPin, wake=wake_param) esp32.wake_on_ext0(pin=self.TactSwPin, level=esp32.WAKEUP_ALL_LOW) TactSwitch.Enabled = False
def __init__(self, machine_config): self.battery_reader = ADC(Pin(35)) self.battery_reader.atten(ADC.ATTN_11DB) self.battery_threshold = machine_config['battery_threshold'] self.battery_led = Pin(machine_config['battery_led'], Pin.OUT) self.battery_level = self.batteryCheck() self.led_strip1 = Pin(machine_config['led_strip1'], Pin.OUT) self.led_strip2 = Pin(machine_config['led_strip2'], Pin.OUT) self.battery_led.value(1) self.power_switch = Pin(machine_config['power_switch'], Pin.IN) esp32.wake_on_ext0(pin=self.power_switch, level=esp32.WAKEUP_ANY_HIGH)
def init() -> None: """ Initialize ESP, reads or creates configuration, sets interrupts. :return: None """ logging.debug("config.py/init()") config.cfg = config.ESPConfig() config.cfg.load_from_file() button = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP) button.irq(trigger=machine.Pin.IRQ_FALLING, handler=button_irq) esp32.wake_on_ext0(pin=button, level=False) button2 = machine.Pin(32, machine.Pin.IN, machine.Pin.PULL_UP) button2.irq(trigger=machine.Pin.IRQ_FALLING, handler=reset_config) esp32.wake_on_ext0(pin=button2, level=esp32.WAKEUP_ALL_LOW) logging.debug("Configuration loaded")
def main(): global i2c, slave_addr, motion i2c = init_i2c_accel() # initialize i2c communication for Accelerometer pin_INT1 = Pin( 35, mode=Pin.IN) # Create an input pin on pin #18 for reading Interrupt esp32.wake_on_ext0(pin=pin_INT1, level=esp32.WAKEUP_ANY_HIGH) # pin_INT1.irq(trigger=Pin.IRQ_RISING, handler=handle_accel_interrupt) # Attach an interrupt to the pin by calling the irq() method if machine.reset_cause() == machine.DEEPSLEEP_RESET: print('Woke from deep sleep') # scan for slave devices devices = i2c.scan() if len(devices) == 0: print("ERROR: No i2c device found!") return (1) else: print('i2c devices found:', devices) print('Connecting to device ', devices[0]) slave_addr = devices[ 0] # Select first device found as slave address to communicate with status = get_accel_status() print(status) # 0x00 = No data available, 0xff: data available accel_config() # Configure Accelerometer settings INT1_status = get_accel_INT1_status() # Reset interrupt by reading count = 0 while True: print("Entering Deep Sleep...") machine.deepsleep() print("Motion detected! % d" % (count)) INT1_status = get_accel_INT1_status() motion = False count = count + 1 time.sleep_ms(10000)
def _configure_pin_interrupt(): esp32.wake_on_ext0(pin=config.WAKEUP_PIN, level=esp32.WAKEUP_ALL_LOW)
from machine import Pin, deepsleep import esp32 import utime # wakeup button wakeup = Pin(25, Pin.IN, Pin.PULL_UP) # esp32 external wakeup esp32.wake_on_ext0(pin=wakeup, level=esp32.WAKEUP_ALL_LOW) # countdown for i in range(10, 0, -1): print('deepsleep in %d seconds' % (i)) utime.sleep(1) # deepsleep for 10 sec print('deepsleep until button press') # deepsleep deepsleep()
except: print("error with ntp sync") flg = False pass #OSError: [Errno 110] ETIMEDOUT js = rtc.datetime print("starting jthings") print("WakeUP Reason: ", machine.wake_reason()) print("wakeup PIN: ", machine.PIN_WAKE) print(sys.implementation.name, sys.implementation.version) ts = rtc.datetime() print(tsstr(rtc.datetime())) id = machine.unique_id() esp32.wake_on_ext0(motion_pir, esp32.WAKEUP_ANY_HIGH) ## setup i2c i2c = i2c_init() i2c_scan(i2c) i2c = I2C(scl=Pin(22), sda=Pin(21), freq=100000) devices = i2c.scan() b = BME280.BME280(i2c=i2c, fmt=False) #evnts = EVENTS("Sensors","fd9a:6f5b:21d1::ee1") evnts = EVENTS("Sensors1", "192.168.1.118", id) evnts.logit(ts, 0, 0, 0, device=500) #Due to limitations of the ESP8266 chip the internal real-time clock (RTC) will overflow every 7:45h. #If a long-term working RTC time is required then time() or localtime() must be called at least once within 7 hours. #MicroPython will then handle the overflow.
def a_dormir(alarma=14, despertar_ms=60000): despertador = Pin(alarma, mode=Pin.IN) esp32.wake_on_ext0(pin=despertador, level=esp32.WAKEUP_ALL_LOW) print('durmiendo') machine.deepsleep(despertar_ms)
if rot_handling: return rot_handling = True clk_cur = pclk.value() if clk_cur != clk_prev and clk_cur == 0: if pdt.value() != clk_cur: scr.cursor_dec() else: scr.cursor_inc() clk_prev = clk_cur scr.update_screen() rot_handling = False pclk.irq( trigger=Pin.IRQ_RISING|Pin.IRQ_FALLING, handler=handle_rotary ) esp32.wake_on_ext0( pin=pclk, level=esp32.WAKEUP_ALL_LOW ) scr = MenuScreen( oled, OLED_WIDTH, OLED_HEIGHT, OLED_CYAN_TOP, rtc, rotary_menu ) scr.menu = rotary_menu while True: try: print( 'updating...' ) dhts.measure() iaq = sgp.indoor_air_quality except Exception as e: print( e ) scr.update_screen()
def run(): oled = Oled(12, 2, 15, 14, 13, 4) ssd = oled.ssd #home=14, left=13 right=11 back=7 key = Key(33, 25, 26, 32) key.start() keyvalue = 15 menu_index = 1 menu = Menu(ssd, jsonfile) def lowpower(ssd): ssd.poweroff() machine.deepsleep() wake1 = Pin(33, mode=Pin.IN) #level parameter can be: esp32.WAKEUP_ANY_HIGH or esp32.WAKEUP_ALL_LOW esp32.wake_on_ext0(pin=wake1, level=esp32.WAKEUP_ALL_LOW) time_cnt = 0 clock = Clock(ssd, key) alarm = Alarm(ssd, key, jsonfile) compass = Compass(ssd, key) weather = Weather(ssd, key, jsonfile) appstore = Appstore(ssd, key, jsonfile) sysset = Sysset(ssd, key, jsonfile) menu_dic = { 1: menu.clock, 2: menu.alarm, 3: menu.compass, 4: menu.weather, 5: menu.appstore, 6: menu.sysset } menu_event = { 1: clock.run, 2: alarm.run, 3: compass.run, 4: weather.run, 5: appstore.run, 6: sysset.run } while True: # time.sleep_ms(200) #time_cnt+=1 #if time_cnt>50: # lowpower(ssd) if key.read() == key.LEFT_PRESS: time_cnt = 0 menu_index = menu_index - 1 if menu_index <= 1: menu_index = 1 time.sleep_ms(200) elif key.read() == key.RIGHT_PRESS: time_cnt = 0 menu_index = menu_index + 1 if menu_index >= 6: menu_index = 6 time.sleep_ms(200) menu.disSensor(90, 0, 0.57) menu_dic[menu_index]() if key.read() == key.HOME_PRESS: time_cnt = 0 ssd.fill(0) menu_event[menu_index]() ssd.fill(0) time.sleep_ms(200)
if not active: do_connect() active = True print(active) print("Switch activated!") time.sleep(1) active = False hue_show() else: print(active) #ds_pin2.irq(trigger=Pin.IRQ_FALLING, handler=callback) #time.sleep(1) callback(None) esp32.wake_on_ext0(pin=ds_pin2, level=esp32.WAKEUP_ALL_LOW) machine.deepsleep() #while True: # pass #v=ds_pin1.value() #print("32: ", v) #v2=ds_pin2.value() # print("33: ", v2)
def sleep(sec): button = machine.Pin(23, machine.Pin.IN) button = machine.Pin(15) button.init(machine.Pin.IN, machine.Pin.PULL_UP) esp32.wake_on_ext0(button, level=0) machine.deepsleep(1000 * sec)
def main(): wdt.feed() if config.app_config["deepsleep"]: esp32.wake_on_ext0(pin=machine.Pin(config.device_config["btn"], machine.Pin.IN), level=esp32.WAKEUP_ALL_LOW) if machine.reset_cause() == machine.DEEPSLEEP_RESET: print('esp32 has been woken from a deep sleep') # cloud connection write_2leds("+", (0, 5, 0)) jwt = create_jwt(config.google_cloud_config['project_id'], config.jwt_config['private_key'], config.jwt_config['algorithm'], config.jwt_config['token_ttl']) client = get_mqtt_client(config.google_cloud_config['project_id'], config.google_cloud_config['cloud_region'], config.google_cloud_config['registry_id'], config.google_cloud_config['device_id'], jwt) gc.collect() # sensor connection write_2leds("+", (0, 0, 5)) bme_sensor.set_gas_heater_profile(320, 120, 0) pms_sensor.wake_up() # acquiring and sending data loop = 0 while True: wdt.feed() machine.freq(160000000) # acquiring data write_2leds("+", (5, 5, 5)) timestamp = utime.time() + epoch_offset bme_data = bme_sensor.measurements pms_data = pms_sensor.measurements[1] message = { "device_id": config.google_cloud_config['device_id'], "timestamp": timestamp, "temp": float(bme_data["temp"]), "hum": float(bme_data["hum"]), "press": float(bme_data["press"]), "gas": float(bme_data["gas"]), "cpm10": int(pms_data["cpm10"]), "cpm25": int(pms_data["cpm25"]), "cpm100": int(pms_data["cpm100"]), "apm10": int(pms_data["apm10"]), "apm25": int(pms_data["apm25"]), "apm100": int(pms_data["apm100"]) } #sending data print("Publishing message " + str(ujson.dumps(message))) write_2leds("+", (5, 0, 0)) mqtt_topic = '/devices/{}/{}'.format( config.google_cloud_config['device_id'], 'events') client.publish(mqtt_topic.encode('utf-8'), ujson.dumps(message).encode('utf-8')) client.check_msg() # Check for new messages on subscription #wating and cleaning gc.collect() write_2leds("-", (0, 0, 5)) utime.sleep_ms(config.app_config["delay"]) # Delay for delay seconds. loop += 1 if loop >= config.app_config["loops"]: loop = 0 write_2leds("+", (2, 2, 2)) print("Going to sleep for about %s milliseconds!" % config.app_config["deepsleepms"]) pms_sensor.power_off() bme_sensor.power_off() if config.app_config["deepsleep"]: utime.sleep_ms(1000) machine.deepsleep(config.app_config["deepsleepms"]) else: sta_if.active(False) machine.freq(20000000) utime.sleep_ms(config.app_config["deepsleepms"]) machine.reset()
def goToSleep(minutes=1): sleepString = 'Sleeping for' + str(minutes) + 'minutes' client.publish(b'/sourSmart/out/response',sleepString.encode('utf-8')) sleep(2) deepsleep(minutes * 60 * 1000) ##### Bootup ### Button setup buttonInput = Pin(35, Pin.IN) buttonInput.irq(trigger=Pin.IRQ_FALLING, handler=buttonJob) esp32.wake_on_ext0(pin = buttonInput, level = esp32.WAKEUP_ALL_LOW) ### Wifi connect utils.connectWifi('CableBox-BF58','ymn5gzm5um') ### MQTT Client setup client = mqttSetup() ### Collect a data point and publish it sensors.sensorCollectionJob() ### Publish current graphs publishGraph(1) ### Set a timer to stay alive for 60 seconds timer = 60
#Task 4.2 Wake up! import esp32 from machine import Pin, deepsleep, DEEPSLEEP_RESET, reset_cause from time import sleep led = Pin(13, Pin.OUT) button = Pin(14, Pin.IN) #Note: with this wake up source, you can only use pins that are RTC GPIOs #take a look at our ESP32 GPIO reference guide. #level parameter can be: esp32.WAKEUP_ANY_HIGH or esp32.WAKEUP_ALL_LOW esp32.wake_on_ext0(pin=button, level=esp32.WAKEUP_ANY_HIGH) # check if the device woke from a deep sleep if reset_cause() == DEEPSLEEP_RESET: print('woke from a deep sleep') print('start work') led.value(1) sleep(5) print('Going to sleep') led.value(0) #put the device to deepsleep deepsleep()
from machine import Pin, deepsleep from time import sleep import esp32 touch_en_p = 25 touch_p = 33 touch = Pin(touch_p, Pin.IN) Pin(touch_en_p, Pin.OUT, Pin.PULL_HOLD, value=1) esp32.wake_on_ext0(pin=touch, level=esp32.WAKEUP_ANY_HIGH) print("Will sleep in 5 seconds") sleep(5) print("Going to sleep") deepsleep()
import machine, time, term, buttons, esp32 import rtcmem # Deep sleep wakeup button gpio = buttons._gpioMap[buttons.BTN_A] pin = buttons._buttons.pin(gpio) esp32.wake_on_ext0(pin=pin, level=0) def clear_boot_magic(): rtcmem.write(0, 0) rtcmem.write(1, 0) def reboot(goHome=True): if goHome: home() else: machine.deepsleep(1) def sleep(duration=0, status=False): if (duration >= 86400000): #One day duration = 0 if status: if duration < 1: term.header(True, "Sleeping until touchbutton is pressed...") else: term.header(True, "Sleeping for " + str(duration) + "ms...") time.sleep(0.1) machine.deepsleep(0)
import machine import esp32 from machine import Pin from time import sleep wake1 = Pin(14, mode = Pin.IN) #level parameter can be: esp32.WAKEUP_ANY_HIGH or esp32.WAKEUP_ALL_LOW esp32.wake_on_ext0(pin = wake1, level = esp32.WAKEUP_ANY_HIGH) #your main code goes here to perform a task print('Im awake. Going to sleep in 10 seconds') sleep(10) print('Going to sleep now') machine.deepsleep()
from m5stack import * from m5ui import * from uiflow import * from machine import * from apps import display import network, urequests, esp32, wifiCfg, i2c_bus, ustruct, gc gc.enable() led = machine.PWM(machine.Pin(10),5000,99) esp32.wake_on_ext0(pin = machine.Pin(39, mode = Pin.IN), level = esp32.WAKEUP_ALL_LOW) lcd.setTextColor(0xaaaaaa, lcd.BLACK) lcd.font(lcd.FONT_Ubuntu) def get_moisture(): i2c = i2c_bus.easyI2C(i2c_bus.PORTA, 0x36) i2c.write_u8(0x0f, 0x10) wait_ms(5) val = i2c.read(2) val = ustruct.unpack(">H", val)[0] return int(val) while(True): axp.setLDO2Volt(3.3) #turn the screen back on while not wifiCfg.doConnect('guest', '12345678', lcdShow=True): pass wait(1) lcd.clear() display.showdata(get_moisture()) moisture = get_moisture() #get moisture try: