badge.init() ugfx.init() esp.rtcmem_write(0, 0) esp.rtcmem_write(1, 0) # setup timezone #timezone = badge.nvs_get_str('system', 'timezone', 'CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00') #time.settimezone(timezone) if badge.safe_mode(): splash = 'splash' else: splash = badge.nvs_get_str('boot', 'splash', 'splash') if machine.wake_reason() == (7, 0): print('[BOOT] Cold boot') import post_ota else: if machine.wake_reason() == (3, 4): print("[BOOT] Wake from sleep (timer)") elif machine.wake_reason() == (3, 1): print("[BOOT] Wake from sleep (button)") else: (reset_cause, wake_reason) = machine.wake_reason() (reset_cause_desc, wake_reason_desc) = machine.wake_description() print("[BOOT] " + str(reset_cause) + ": " + reset_cause_desc + ", " + str(wake_reason) + ": " + wake_reason_desc) load_me = esp.rtcmem_read_string() if load_me: splash = load_me
else: # For sleep, setup once and go in loop client = FireSensor() client.setup_from_remote() start = time.ticks_ms() while True: if time.ticks_diff(start, time.ticks_ms()) > SLEEP_DELAY: client.request_config( ) # After timeout, get updated settings from server start = time.ticks_ms() client.check_sensor() else: # Recover from deepsleep reason = machine.wake_reason()[0] if reason == machine.PIN_WAKE: print("Wake on PIN_INTERRUPT") client = FireSensor() # If not configured, get settings from remote client.setup_from_remote() # Take measurement, notify remote and go back to sleep client.check_sensor() else: print("Wake on deep sleep timeout") client = FireSensor() client.request_config(
from machine import RTC from machine import Pin import pycom import time import machine pycom.heartbeat(False) # stop the heartbeat # Set up the Real Time Clock (RTC) rtc = RTC() print(rtc.now()) # This will print date and time if it was set before going # to deepsleep. The RTC keeps running in deepsleep. # rtc.init((2019, 3, 11, 15, 39)) # manually set the time print("wake reason (wake_reason, gpio_list):", machine.wake_reason()) ''' PWRON_WAKE -- 0 PIN_WAKE -- 1 RTC_WAKE -- 2 ULP_WAKE -- 3 ''' # blink the led for cycles in range(2): # stop after 2 cycles pycom.rgbled(0x007f00) # green time.sleep(1) pycom.rgbled(0x7f7f00) # yellow time.sleep(1) pycom.rgbled(0x7f0000) # red time.sleep(1) # # # We now want to set the user button on the Expansion Board as a button
def log(): import machine, utime, esp, esp32, urequests, usocket, network, uos import bme280, ms5803, post_to_google_sheet from machine import Pin led = Pin(5, Pin.OUT) led.value(0) def flash(n, t): for i in range(n): led.value(1) utime.sleep(t) led.value(0) utime.sleep(t) esp.osdebug(None) startticks = utime.ticks_ms() #declare global login variables ssid = "Sensors" password = "******" gKey = "AKfycbwAJbCuZfNzar00oHPd3CZ8Hzn9c79LfUU5lg8u0p9kAxiGyetqGqWJ" gSheetKey = "1AIWnPTtGNdlZ1TfbzpGTnheCOrPnKUHLUVefa8i2Y8k" wake_reason = machine.wake_reason() reset_cause = machine.reset_cause() print('wake reason = ' + str(wake_reason)) print('reset cause = ' + str(reset_cause)) #mount SD card on Lolin D32 Pro. If it doesn't work, sleep 20 seconds so user can break out. try: uos.mount( machine.SDCard(slot=2, width=1, sck=18, mosi=23, miso=19, cs=4), "/sd") except: flash(20, 0.25) #write header file if did not wake from deep sleep if machine.reset_cause != machine.DEEPSLEEP_RESET: outputtxt = 'date,time,Patm(mbar),Tatm(C),PH20(mbar),TH20(C),Depth(m),Battery(V)\r\n' try: uos.chdir('sd') f = open('datalog.txt', 'a') f.write(outputtxt) f.close() uos.chdir('/') except: #flash LED if fails to write and write to flash memory f = open('datalog.txt', 'a') f.write(outputtxt) f.close() flash(10, 0.5) #turn on power pins for RTC power = Pin(2, Pin.OUT) power.value(1) #connect to wlan try: sta_if = network.WLAN( network.STA_IF) #define object to access station mode functions sta_if.active(True) #make station mode active sta_if.connect(ssid, password) print('connected') except: print('not connected') pass utime.sleep(3) #read value of time from DS3231 RTC if it is connected. If not, set time from #web (NTP time) and if that doesn't work, just revert to system real time clock. try: import urtc #needs to be on the board from machine import I2C, Pin i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000) rtc = urtc.DS3231(i2c) datetime = rtc.datetime() print('Time set from DS3231') except: try: from ntptime import settime print('Time set from NTP time to: ', end='') settime() utime.sleep_ms(500) rtc = machine.RTC() #can also set time manually using rtc.datetime(year, month, day, weekday, hour, minute, second, millisecond) except: print( "could not set time from NTP server, reverting to machine RTC for time" ) rtc = machine.RTC() datetime = rtc.datetime() print('Datetime in machine.rtc format = ', end='') print(datetime) #read value of voltage using built-in 100k 100k voltage divider on pin 35 for Lolin D32 Pro from machine import ADC adc = ADC(Pin(35)) adc.atten(ADC.ATTN_11DB) #Voltage range 0 (0) V to 3.6 V (4095) adc_count = adc.read() battery = adc_count / 4095 * 3.6 * 2 #factor of two because of voltage divider print('battery = ', battery) #Read data i2c = machine.I2C(1, scl=machine.Pin(22), sda=machine.Pin(21)) bad = False try: bme1 = bme280.BME280(i2c=i2c, address=119) #sdo to 3.3v [T1, P1, H1] = bme1.raw_values #T in degrees C, P in hPa except: [T1, P1, H1] = [-999, -999, -999] bad = True try: [P2, T2] = ms5803.read(i2c=i2c, address=118) except: [P2, T2] = [-999, -999] bad = True if not bad: WaterLevelDifference = (P2 - P1) * 100 / 9810 else: WaterLevelDifference = -999 data = {} data['Patm'] = P1 data['Tatm'] = T1 data['PH20'] = P2 data['TH20'] = T2 data['Depth'] = WaterLevelDifference data['Battery'] = battery #Send data to Google Sheet result = post_to_google_sheet.send_to_sheet(ssid, password, gKey, gSheetKey, data) print(result) #turn off wifi to lower power when in sleep mode sta_if.active(0) #format output string outputtxt = ('%s/%s/%s,%s:%s:%s,' % (datetime[0], datetime[1], datetime[2], datetime[4], datetime[5], datetime[6])) outputtxt += ('%s,%s,%s,%s,%s,%s\r\n' % (P1, T1, P2, T2, WaterLevelDifference, battery)) print(outputtxt) #then write final data to the SD try: uos.chdir('sd') f = open('datalog.txt', 'w') #this erases the old file f.write(outputtxt) #only first line of file is used f.close() uos.chdir('/') except: #flash LED if fails to write and write to flash memory f = open('datalog.txt', 'a') f.write(outputtxt) f.close() flash(10, 0.5) flash(5, 1) p1 = machine.Pin(15, machine.Pin.IN, machine.Pin.PULL_UP) #esp32.wake_on_ext0(p1, level = 0) #set machine to wake if p1 (so pin 15) is pulled low #the internal pull-up resistor may not work, so may require #an external pull-up resistor of perhaps 100K. esp32.wake_on_ext1([p1], level=0) timeon = (utime.ticks_ms() - startticks) / 1000 print('Going to sleep after being awake for ' + str(timeon) + ' s') machine.deepsleep(1000 * 1 * 60) #sleeps 5 minutes
def turn_to_MAC(data): return ':'.join('%02x' % b for b in data) def connect_wifi(): wifi = network.WLAN(network.STA_IF) wifi.active(True) wifi.connect('MSI 6365','172K%2f8') if wifi.isconnected(): print('Oh Yes! Get connected') print('Connected to', wifi.config('essid')) mac_address = turn_to_MAC(wifi.config('mac')) print('MAC Address:', mac_address) print('IP Address:', wifi.ifconfig()[0]) connect_wifi() if machine.wake_reason() == 4: print('Timer wake-up') green_led = Pin(14,Pin.OUT) green_led.on() pushbutton1 = Pin(36,Pin.IN,Pin.PULL_DOWN) pushbutton2 = Pin(4,Pin.IN,Pin.PULL_DOWN) red_led = Pin(21,Pin.OUT) red_led.on() touch = TouchPad(Pin(15)) touch2 = TouchPad(Pin(32)) touch.config(400) touch2.config(500) esp32.wake_on_touch(True) tm = ntptime.time()
do_connect() test_dns() # http_get() #kasa = Kasa() #kasa.on() ################################################################ # MAIN ################################################################ wakeup_reason_candidates = ['PIN', 'PWRON', 'RTC', 'ULP', 'WLAN'] reset_cause_candidates = [ 'PWRON', 'HARD', 'SOFT', 'WDT', 'DEEPSLEEP', 'BROWN_OUT' ] wake = wakeup_reason_candidates[machine.wake_reason()] reset = reset_cause_candidates[machine.reset_cause()] timer = Timer(0) print(wake, reset) if reset == "DEEPSLEEP": try: machine.freq(240000000) sd = SoundDetector(HZ=7500, min_freq=3000, max_freq=3200, min_amp=300, led=ledb) # timer.init(period=2000, mode=machine.Timer.PERIODIC, callback=blink_white) sd.listen(60 * 1000, [kasa_listener], early_stop=True) del sd
np.set(0, 0xFF0000) np.show() import network import gc #connect sta = network.WLAN(network.STA_IF) sta.active(True) wlan=list() with open( 'credentials.txt','r') as f: # this file should contain ssid<space>pw, one per line line=f.readline().strip().split() while line: wlan.append(line) line=f.readline().strip().split() if machine.wake_reason()[0] not in [4,6]:#Soft reset # this should help reconnecting... not sure whether it works or not # configuration below MUST match your home router settings!! print('configure wlan') sta.ifconfig(('192.168.178.53', '255.255.255.0', '192.168.178.1', '8.8.8.8')) timeout=5000 #5 seconds if not sta.isconnected(): # try all wlans from the file # todo: scan first and check which can be seen for pw in wlan: start = time.ticks_ms() while not sta.isconnected(): sta.connect(*pw) print('connecting to wlan, ip is {}'.format(sta.ifconfig()[0])) for i in range(5):
__version__ = "0." + "$Revision: 5.6 $"[11:-2] __license__ = 'GPLV3' ''' basis PyCom LoPy controller and PCB test. if deepsleep pin not is enabled, no update of config file will be done. If no accu is attached and deepsleep pin is enabled flashed config file will be cleared. ''' from machine import deepsleep, wake_reason, PWRON_WAKE wokeUp = wake_reason()[0] != PWRON_WAKE if wokeUp: print("Woke up from deepsleep.") else: print("Cold reboot") ################## json flashed configuration # roll in archive configuration try: import ConfigJson except: print("Missing library led and/or ConfigJson") sys.exit() MyConfig = ConfigJson.MyConfig(archive=(not wokeUp), debug=False) config = MyConfig.getConfig() # configuration if config: print("Got config from flash: %s" % str(config)) ####################### RGB led import sys from time import time, sleep # Turn off hearbeat LED import pycom pycom.heartbeat(False) LED = None try:
received_cmd = [ ] # Array destined to collect the commands sent by the server return master_dict, wakeup_count, data, commands, received_cmd #____________________________________________________________________________________________________ #_____________________________________________MAIN_CODE______________________________________________ try: # Checking if there are already data in flash memory or if there's a reinitilization try: master_dict = permmem.read_in_flash(filename) except OSError: print('First boot.\n') first_boot = True else: if not machine.wake_reason() == machine.PIN_WAKE: print('Normal wakeup. Booting data:\n') print(master_dict) board.led_green() wakeup_count, data, commands, received_cmd, url_send, wifi_param, config = permmem.open_dict( master_dict) else: reinit = True # Initialisation if needed if reinit or first_boot: print('Initialise.\n') board.led_red() master_dict, wakeup_count, data, commands, received_cmd = variables_init( )
equationParameters = slope(config) print('equationParameters', equationParameters) logsDir() ###########---CALIBRACIÓN DEL CRONÓMETRO PARA LA TOMA DE DATOS---############### global measurementTime #tiempo en minutos para la adquisión de datos. measurementTime = 5 sendTime = measurementTime #tiempo para hacer la transmision [minutos] P8 = Pin('P8', mode=Pin.IN, pull=Pin.PULL_UP) machine.pin_deepsleep_wakeup([P8], machine.WAKEUP_ALL_LOW, True) wifiMain = False ###########################----WAKEREASON_PIN----############################### #Test a P8 durante 3[segundos] para confirmar la activación del WiFi if machine.wake_reason()[0] == 1: print('PIN sleep') i = 0 while P8() == 0: print('dentro del while') pycom.rgbled(0x009999) # blue time.sleep(0.5) pycom.rgbled(False) time.sleep(0.5) i = i + 1 if i == 3: pycom.rgbled(0x009900) # RED time.sleep(1) pycom.rgbled(False) time.sleep(1) wifiMain = True
wifi = WLAN() print(machine) machine.idle() print(machine.freq() == (80000000,)) print(machine.unique_id() == wifi.mac()) machine.main('main.py') rand_nums = [] for i in range(0, 100): rand = machine.rng() if rand not in rand_nums: rand_nums.append(rand) else: print('RNG number repeated') break for i in range(0, 10): machine.idle() print("Active") print(machine.reset_cause() >= 0) print(machine.wake_reason() >= 0) try: machine.main(123456) except: print('Exception')
except: pass try: from Config import replPin # if not in config act in old style if not Pin(replPin, mode=Pin.IN).value(): print("REPL enforced, pin %s" % str(REPL)) return True except: pass return REPL from machine import wake_reason, PWRON_WAKE, RTC_WAKE try: from pycom import wifi_on_boot if (not wifi_on_boot()) and (wake_reason()[0] == PWRON_WAKE): wifi_on_boot(True) # wokeup from power cycle, reset wifi if ReplMode() or wifi_on_boot(): setWiFi() # might be switched off after 60 min except: setWiFi() def runMySense(): import MySense MySense.runMe() # should never return import myReset # cold reboot or sleep forever myReset.myEnd() from machine import wake_reason, PWRON_WAKE, RTC_WAKE
def test_flash_detection(): if machine.wake_reason()[0] == machine.PIN_WAKE: flash_detect_main()
# Set timezone rtc = machine.RTC() if (rtc.timezone() == ""): rtc.timezone( badge.nvs_get_str('system', 'timezone', 'CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00')) # Check if the badge is booted in safe mode if badge.safe_mode(): splash = 'dashboard.launcher' else: splash = badge.nvs_get_str('boot', 'splash', 'dashboard.home') # Check if started from cold or warm boot if machine.wake_reason() == (7, 0): import post_ota else: load_me = esp.rtcmem_read_string() if load_me: splash = load_me print("starting %s" % load_me) esp.rtcmem_write_string("") try: if not splash == "shell": if splash.startswith('bpp '): splash = splash[4:len(splash)] badge.mount_bpp() elif splash.startswith('remfs '): splash = splash[6:len(splash)]
from network import LoRa import machine import socket import ubinascii import struct #lower power consumption pycom.heartbeat(False) pycom.rgbled(0x000000) pycom.wifi_on_boot(False) ###########VARS################# receivedData =[] ###########SETUP RFM################ if machine.wake_reason()[0] == 0: #If the LoPy just got startet, configure RFM69 and go to deepsleep for power saving print("Gerade hochgefahren, führe Setup durch") rfm = RFM69.RFM69(RF69_433MHZ, 1, 42, False) results = rfm.readAllRegs() for result in results: print(result) rfm.rcCalibration() rfm.setHighPower(True) rfm.encrypt("sampleEncryptKey") rfm.receiveBegin() f = open('/flash/data.csv', 'w') f.write('') f.close() print("Gute Nacht") machine.pin_deepsleep_wakeup(['P9'], machine.WAKEUP_ANY_HIGH) machine.deepsleep(200000)
wifi = WLAN() print(machine) machine.idle() print(machine.freq() == (80000000, )) print(machine.unique_id() == wifi.mac()) machine.main("main.py") rand_nums = [] for i in range(0, 100): rand = machine.rng() if rand not in rand_nums: rand_nums.append(rand) else: print("RNG number repeated") break for i in range(0, 10): machine.idle() print("Active") print(machine.reset_cause() >= 0) print(machine.wake_reason() >= 0) try: machine.main(123456) except: print("Exception")
def _run_tasks(forever): while True: if _tasks: first_task = _tasks[0] time_until_first_task = first_task.seconds_since_epoch - utime.time( ) if time_until_first_task <= 0: # remove the first task from the list _tasks.pop(0) # Schedule the task at the next execution time if it is a repeating task. # This needs to be done before executing the task so that it can remove itself # from the scheduled tasks if it wants to. if first_task.repeat_after_sec != 0: schedule_at_sec( first_task.module_name, first_task.function_name, first_task.seconds_since_epoch + first_task.repeat_after_sec, first_task.repeat_after_sec) successful = _execute_task(first_task) if not successful and first_task.repeat_after_sec != 0: # the task was added already so on failure we remove it remove_all(first_task.module_name, first_task.function_name) else: # - 1 below is to wake up one second before the task executes if allow_deep_sleep and time_until_first_task > 1: if (not machine.wake_reason() == machine.DEEPSLEEP_RESET and utime.time() < _start_seconds_since_epoch + initial_deep_sleep_delay_sec): # initial deep sleep delay remaining_no_deep_sleep_sec = ( _start_seconds_since_epoch + initial_deep_sleep_delay_sec) - utime.time() if (time_until_first_task - 1 > remaining_no_deep_sleep_sec): # deep sleep prevention on cold boot print("sleepscheduler: sleep({}) due to cold boot". format(remaining_no_deep_sleep_sec)) utime.sleep(remaining_no_deep_sleep_sec) else: print("sleepscheduler: sleep({}) due to cold boot". format(time_until_first_task - 1)) utime.sleep(time_until_first_task - 1) else: _deep_sleep_sec(time_until_first_task - 1) else: if time_until_first_task > 1: print("sleepscheduler: sleep({})".format( time_until_first_task - 1)) utime.sleep(time_until_first_task - 1) else: # wait in ms to execute the task when the next second starts first_task_seconds_since_epoch = first_task.seconds_since_epoch while first_task_seconds_since_epoch - utime.time( ) > 0: utime.sleep_ms(1) else: if forever: # deep sleep until an external interrupt occurs (if configured) _store() print("sleepscheduler: Deep sleep infinitely") machine.deepsleep() else: print( "sleepscheduler: All tasks finished, exiting sleepscheduler." ) break
# Init sensor on pins according to nde version if my_config_dict['node_version'] == 0x01: i2c_irt = I2C(0, I2C.MASTER, pins=('P22', 'P21')) i2c_air = I2C(1, I2C.MASTER, pins=('P20', 'P19')) ow = OneWire(Pin('P23')) elif (my_config_dict['node_version'] == 0x03) or (my_config_dict['node_version'] == 0x02): i2c_irt = I2C(0, I2C.MASTER, pins=('P21', 'P22')) i2c_air = I2C(1, I2C.MASTER, pins=('P19', 'P20')) ow = OneWire(Pin('P11')) if DEBUG_MODE: debug_info = {'i2c_irt': scan_i2c(i2c_irt), 'i2c_air': scan_i2c(i2c_air)} print(debug_info) wake_s = machine.wake_reason() reset_s = machine.reset_cause() if reset_s == machine.WDT_RESET: status_flag |= status.WDT_ERROR print(wake_s) print() # create an OTA authentication params for this node dev_eui = ubinascii.unhexlify(my_config_dict['dev_eui'].replace(' ', '')) app_eui = ubinascii.unhexlify(my_config_dict['app_eui'].replace(' ', '')) app_key = ubinascii.unhexlify(my_config_dict['app_key'].replace(' ', '')) print_lorawan()
# tested on TTGO TDisplay from machine import Pin, deepsleep, wake_reason import esp, esp32 from time import sleep pir = Pin(13, Pin.IN, Pin.PULL_UP) btn = Pin(12, Pin.IN) print('Wake from deepsleep... reasons.') esp.osdebug(None) while True: reason = wake_reason() print('Wake Reason =', reason) if reason == 3: print('button') if reason == 2: print('PIR') sleep(5) esp32.wake_on_ext0(pin=pir, level=esp32.WAKEUP_ANY_HIGH) esp32.wake_on_ext1(pins=(btn, ), level=esp32.WAKEUP_ANY_HIGH) print('going to sleep') deepsleep()
rtc = machine.RTC() ntptime.host = '192.168.1.118' try: ntptime.settime() flg = True print("time set with ntp sync") 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")
# boot.py -- run on boot-up # can run arbitrary Python, but best to keep it minimal print("-- performing boot --") # acces the (ESP32) hardware functionality using the machine library import machine # read the reset, wake = machine.wake_reason() #as an exaple it is possible to determine how/why the microcontroller was started or woken up if reset == 0: print('Power On') elif reset == 1: print('Hard reset') elif reset == 6: print('Soft reset') if wake == 3: print('woken by Touchpad') print("-- end of boot.py --")
if (machine.reset_cause()==machine.DEEPSLEEP_RESET): saved_data=machine.RTC().memory() print ("woken with data") print(saved_data) split_data = saved_data.split(b',') if (len(split_data) == 4): print ("restoring data", split_data) door_last_open_time = int(split_data[0]) current_notification_state=int(split_data[1]) #door_open = split_data[2] == b'True' connection_failure_count = int(split_data[3]) if (machine.wake_reason() == machine.PIN_WAKE): if (sensor.value() == 1): print ("woke and realized the door was open") door_last_open_time = utime.time() current_notification_state = 0 door_open=True connection_failure_count = 0 sleepytime = notification_delays[current_notification_state]- (time.time()-door_last_open_time) print ("sleeping for %d seconds waiting for first notification" % sleepytime) save_and_sleep(machine.Pin.WAKE_LOW, sleepytime) else: door_open = False print ("woke and realized the door was closed, went to sleep") save_and_sleep(machine.Pin.WAKE_HIGH, 0) if(machine.wake_reason() == machine.TIMER_WAKE):
tpin = TouchPad(Pin(27)) tpin_green = TouchPad(Pin(33)) # configure the threshold at which the pin is considered touched tpin.config(500) esp32.wake_on_touch(True) #External button wake-up esp32.wake_on_ext1(pins = (button_red, button_green), level = esp32.WAKEUP_ANY_HIGH) #Red led turns on red.value(1) #Hardware timer - 2 tim2 = Timer(2) tim2.init(period=10, mode=Timer.PERIODIC, callback=handletouch) # #Hardware timer - 3 tim3 = Timer(3) tim3.init(period=30000, mode=Timer.PERIODIC, callback=handlesleep) # check if the device woke from a deep sleep if machine.wake_reason() == 5: print('Touchpad Wake-up') elif machine.wake_reason() == 3: print('EXT1 Wake-up') elif machine.wake_reason() == 4: print('Timer Wake-up')
elif mrc == machine.HARD_RESET: print("HARD_RESET") elif mrc == machine.WDT_RESET: print("WDT_RESET") # machine.reset() # machine.lte_reset() elif mrc == machine.DEEPSLEEP_RESET: print("DEEPSLEEP_RESET") # machine.deepsleep() elif mrc == machine.SOFT_RESET: print("SOFT_RESET") # Ctrl-D elif mrc == machine.BROWN_OUT_RESET: print("BROWN_OUT_RESET") mwr = machine.wake_reason() print("wake_reason", mwr, end=' ') if mwr[0] == machine.PWRON_WAKE: print("PWRON_WAKE") # reset button elif mwr[0] == machine.PIN_WAKE: print("PIN_WAKE") elif mwr[0] == machine.RTC_WAKE: print("RTC_WAKE") # from deepsleep elif mwr[0] == machine.ULP_WAKE: print("ULP_WAKE") print("===== os =========================================") print("sysname", os.uname().sysname) # e.g., GPy print("release", os.uname().release) # e.g., 1.20.1.r1
import machine, sys, system, time, buttons, samd rtc = machine.RTC() rtc.write(0,0) rtc.write(1,0) __chk_recovery = False if machine.nvs_getint("system", 'factory_checked'): __chk_recovery = machine.wake_reason() == (7, 0) and buttons.value(buttons.BTN_OK) samd.backlight(255) #Application starting if __chk_recovery: app = "dashboard.recovery" else: app = rtc.read_string() if not app: if not machine.nvs_getint("system", 'factory_checked') == 2: app = "factory_checks" else: app = machine.nvs_getstr("system", 'default_app') if not app: app = 'dashboard.home' if app and not app == "shell": try: print("Starting app '%s'..." % app) system.__current_app__ = app if app:
import pycom # Deactivate LED pycom.heartbeat(False) # Variables pin_str = 'P18' pir = Pin(pin_str, mode=Pin.IN, pull=None) device_found = False wlan = WLAN(mode=WLAN.STA, antenna=WLAN.EXT_ANT) lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) app_eui = ubinascii.unhexlify(config.app_eui) app_key = ubinascii.unhexlify(config.app_key) s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # 1 if interrupted by PIR, 2 if timeout wake_reason = machine.wake_reason()[0] # True if motion's been detected. False if not. high = True if machine.wake_reason()[1] != [] else False # Function for wifi-sniffer def pack_cb(pack): global device_found pk = wlan.wifi_packet() control = pk.data[0] subtype = (0xF0 & control) >> 4 #print("Control:{}, subtype:{}, type:{}".format(control, subtype, type)) if subtype == 4: device_found = True
rtc = machine.RTC() rtc.write(0, 0) rtc.write(1, 0) __chk_recovery = False if machine.nvs_getint("system", 'factory_checked'): try: import buttons try: #Use the START button if available recovery_button = buttons.BTN_START except: #Else use the B button recovery_button = buttons.BTN_B __chk_recovery = machine.wake_reason() == ( 7, 0) and buttons.value(recovery_button) except: pass #Application starting if __chk_recovery: app = "dashboard.recovery" else: app = rtc.read_string() if not app: if not machine.nvs_getint("system", 'factory_checked') == 2: app = "factory_checks" else: app = machine.nvs_getstr("system", 'default_app') if not app:
def isColdBoot(): if machine.wake_reason() == (7, 0): return True return False
""" TOCS example usage """ import machine from machine import Pin import time Wake_reason = { 0: 'None', machine.PWRON_WAKE: 'PWRON_WAKE', machine.PIN_WAKE: 'PIN_WAKE', machine.RTC_WAKE: 'RTC_WAKE', machine.ULP_WAKE: 'ULP_WAKE' } print("Wake reason is: %s and remaining sleep duration = %s" % (Wake_reason[machine.wake_reason()[0]], machine.remaining_sleep_time())) def pin_handler(arg): time.sleep(0.5) print("Setting %s to listen for wakeup" % (arg.id())) machine.pin_deepsleep_wakeup([arg.id()], machine.WAKEUP_ALL_LOW, True) print("Going into deepsleep: %s" % (arg.id())) machine.deepsleep(10000) p_in = Pin('P10', mode=Pin.IN, pull=Pin.PULL_UP) p_in.callback(Pin.IRQ_FALLING, pin_handler)
def display_info(self): gc.collect() output = dict( freq=int(machine.freq() / 1_000_000), flash=esp.flash_size(), hall=esp32.hall_sensor(), temp=int((esp32.raw_temperature() - 32) / 1.8), mac=self.network.mac, ip=self.network.ip, ram=gc.mem_free(), ) output = ["%s: %s" % (key, val) for key, val in output.items()] self.screen.display_lines(output) print("wake reason", machine.wake_reason()) help("modules") import builtins dir(builtins) dir(machine) dir(esp) dir(esp32) App().run() # machine.deep_sleep(30_000)
msg = (b'{{ "idx": {}, "nvalue": 0, "svalue": "{}" }}'.format(idx, mode)) print(msg) print("Posting current heating mode to domoticz") if mode: client.publish(TOPIC, msg) # Publish sensor data to MQTT topic return True else: print("Error loading saved mode") return False print("Starting One wire module with embeded temperature sensor") if DEBUG: machine.loglevel('*', machine.LOG_DEBUG) if 4 == machine.wake_reason()[0]: print('Woke from a deep sleep') else: print("Woke up from hard reboot ?") utime.sleep(2) pin = machine.Pin(LED_BUILT_IN, machine.Pin.OUT) # Initialize the MOC3043 Pins alt_positive_pin = machine.Pin(ALT_POSITIVE_PIN, machine.Pin.OUT) alt_negative_pin = machine.Pin(ALT_NEGATIVE_PIN, machine.Pin.OUT) current_mode = default_mode() # the temperature device is on GPIO16 dat = machine.Pin(DS18B20_PIN, machine.Pin.IN) # create the onewire object ow = machine.Onewire(dat)