def boot(): gc.collect() log.setup() # config.setup() # Setup display display.setup() log.success("display setup") display.text("wifi") wifi.setup() log.info("trying to connect to wifi") for _ in range(25): if wifi.isconnected(): log.success("connected to wifi {}".format(wifi.get_wifi_ip())) break machine.sleep(200) else: log.error("could not connect to wifi") return # pylint: disable=no-member #asyncio.get_event_loop().run_until_complete( # display.scroll_text("{}".format(wifi.get_wifi_ip()))) machine.sleep(500) # Set time display.text("time") clock.setup() log.success("time is synced") display.text("done")
def update(self, delta=0): self.display.fill(display.BACKGROUND) if self.storage.NAME == 'HOWDOITURNTHISON': self.display.image( 'AAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAAAf////wAAAAAAAAAAAAAAAAAAAAAAAAAAPwAAAAB/////AAAAAAAAAAAAAH////wAAAAAAAD/AAf///+Gf////AAAAAAAAAAAf////AAAAAAAAP8AB////4Z////8AAAAAAAAAAf/h////////AAB////////////////wAAAAAAAB/+H///////8AAH////////////////AAAAAAAB///////////6/9/////////////////+AAAAAAH///////////////////////////////8AAAAAH////+AAf/g//////////+AAf/gP4P////AAAAAf////4AB/+D//////////4AB/+A/g////8AAAAH4f+H/////////////////////////////8AAAAfh/4f/////////////////////////////wAAAHgH////////////////////////////////wAAAeAf////////////////////////////////AAAHAB/////////////////////////////////AAAcAH////////////////////////////////8AAHgAf////////////////////////////////wAAeAB/////////////////////////////////AAB4AH//////////z/////////////////////8AAHgf///////////P/////////////////////8AAaB//////////////////////////////////wAHgf//////////////////4AHg////////////wAeH///////////z////5//////////////////AB4f///////////P////n/////////////////8AeH/7/////////z///////////////////////wB4f/n/////////P///////////////////////AHh/+f////////////////////////////////9AeH/5/////////////////////////////////8B4f/v/////////////////////////////////wf/////////////////////////////////////Bh3/5////////+P////+///////+//////////8EAAAB+AAAAAAAA/////wAAAAAAAAf/////8AAAwQAAAH4AAAAAAAD/////AAAAAAAAB//////wAADMAAAAeAAAAAAAA/////wAAAAAAAAH//////AAAMwAAAB4AAAAAAAD/////AAAAAAAAAf/////8AAAzAAAAGAAAAAAAAP////8AAAAAAAAB//////wAADMAAAAYAAAAAAAD/////gAAAAAAAAH//////AAAMwAAABgAAAAAAAP////8AAAAAAAAAf/////8AAAzAAAAAAAAAAAAA/////wAAAAAAAAB//////wAADMAAAAAAAAAAAAD/////AAAAAAAAAB//////AAAMwAAAAAAAAAAAAP////+AAAAAAAAAH/////8AAAzAAAAAAAAAAAAA/////8AAAAAAAAAf/////wAAA8AAAAAAAAAAAAD/////wAAAAAAAAB//////AAADwAAAAAAAAAAAA//////AAAAAAAAAH/////8AAAPAAAAAAAAAAAAD/////8AAAAAAAAAf/////wAAA8AAAAAAAAAAAAP/////AAAAAAAAAB//////AAADwAAAAAAAAAAAA/////+AAAAAAAAAH/////8AAAPAAAAAAAAAAAAD/////wAAAAAAAAAf/////wAAA8AAAAAAAAAAAAf/////AAAAAAAAAB//////AAAD//+f//////////////8//////////////////////5///////////////z//////////////////////n///////////////P///////////////////7/+f//////////////8////////////////////AAAAAAAAAAAAD/////4AAAAAAAAAf/////wAAA8AAAAAAAAAAAAP/////AAAAAAAAAB//////AAADwAAAAAAAAAAAA/////8AAAAAAAAAH/////8AAAPAAAAAAAAAAAAD/////4AAAAAAAAAf/////wAAA8AAAAAAAAAAAAP/////wAAAAAAAAB//////AAADwAAAAAAAAAAAA//////AAAAAAAAAH/////8AAAPAAAAAAAAAAAAA/////8AAAAAAAAAf/////wAAA8AAAAAAAAAAAAD/////wAAAAAAAAB//////AAADwAAAAAAAAAAAAP////+AAAAAAAAAH/////8AAAzAAAAAAAAAAAAA/////wAAAAAAAAAf/////wAADMAAAAYAAAAAAAD/////gAAAAAAAAH//////AAAMwAAABgAAAAAAAP////+AAAAAAAAAf/////8AAAzAAAAGAAAAAAAAP////8AAAAAAAAB//////wAADMAAAAYAAAAAAAA/////wAAAAAAAAH//////AAAMwAAAB4AAAAAAAD/////AAAAAAAAAf/////8AAAzAAAAHgAAAAAAAP////8AAAAAAAAB//////wAADBAAAAfgAAAAAAAP////8AAAAAAAAH//////AAAMEAAAB+AAAAAAAA/////wAAAAAAAAf/////8AAAwf/////////////////////////////////////B/////////////////////////////////////8B4f/n/////////////////////////////////wHh/+f/////////////////////////////////AeH/5/////////z///////////////////////wB4f/n/////////P///////////////////////AB4/////////////////n/////////////////8AHh///////////8////+f/////////////////wAeB///////////3////7//gAeH////////////AB4H//////////////////+AB4f///////////8AHgf///////////////////AH/////////////gAfgf///////////P/////////////////////8AAeAB/////////////////////////////////AAB4AH////////////////////////////////8AABwAf////////////////////////////////wAAHAB/////////////////////////////////AAAHAH////////////////////////////////wAAAeAf////////////////////////////////AAAAYB/4f/////////////////////////////wAAAB+H/h//////////////////////////////AAAAB4f+P/0AH/8f///////////////3/X////wAAAAH////+AAf/g//////////+AAf/gP4P////AAAAAf////4AB//D//////////4AB/+B/g////8AAAAAH///////////////////////////////8AAAAAAB/+H///////8AAH////////////////AAAAAAAAH/4P///////wAAf///////////////8AAAAAAAAB////8AAAAAAAA/wAH////j3////wAAAAAAAAAAH////wAAAAAAAD/AAf///+Gf////AAAAAAAAAAAAAAAAAAAAAAAAD8AAAAAf////wAAAAAAAAAAAAAAAAAAAAAAAAAAPwAAAAB/////AAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAA=', 32, 11, 232, 106) elif self.storage.IMAGE and len(self.storage.IMAGE) > 0: self.display.image(self.storage.IMAGE) else: name = self.storage.NAME if name is None or name == '': name = 'Anonymous\n Trooper' self.display.font(display.FONT_DEJAVU_42) if len(name) > 22: self.display.font(display.FONT_DEJAVU_24) space = 32 size = self.display.text(name, x=space, y=0, max_width=self.display.width - 2 * space, wrap=display.WRAP_INDENT) self.display.fill(display.BACKGROUND) x = self.display.width // 2 - size['width'] // 2 y = self.display.height // 2 - size['height'] // 2 self.display.text(name, x=x, y=y, max_width=self.display.width - 2 * space, wrap=display.WRAP_INDENT) self.display.update() machine.sleep()
def test(): scl = machine.Pin(27, machine.Pin.IN, machine.Pin.PULL_UP) sda = machine.Pin(26, machine.Pin.IN, machine.Pin.PULL_UP) i2c = machine.SoftI2C(scl=scl, sda=sda, freq=400000) sensor = SHT3XDIS(i2c) sensor.reset() machine.sleep(20) sensor.clear() machine.sleep(20) print(sensor.status) print(sensor.values)
def go_to_sleep(self): self.log("Going to sleep...") self.store_settings() if USE_DEEPSLEEP: if SLEEP_DELAY == 0: machine.deepsleep() else: machine.deepsleep(SLEEP_DELAY) else: if SLEEP_DELAY == 0: machine.sleep() else: machine.sleep(SLEEP_DELAY)
def wlan_connect(): wifi = WLAN(mode=WLAN.STA) wifi.ifconfig(config=(__myip, __netmask, __gateway, __dns)) wifi.scan() # scan for available networks wifi.connect(ssid=__ssid, auth=(WLAN.WPA2, __nwpass)) while not wifi.isconnected(): pass syslog('WiPy is up and running') wifi.irq(trigger=WLAN.ANY_EVENT, wake=machine.SLEEP) machine.sleep()
def hibernate(self, interval, lightsleep=False, deepsleep=False): """ :param interval: :param lightsleep: (Default value = False) :param deepsleep: (Default value = False) """ #logging.enable_logging() if deepsleep: # Prepare and invoke deep sleep. # https://docs.micropython.org/en/latest/library/machine.html#machine.deepsleep log.info('Preparing deep sleep') # Set wake up mode. self.set_wakeup_mode() # Invoke deep sleep. log.info('Entering deep sleep for {} seconds'.format(interval)) #self.terminal.stop() machine.deepsleep(int(interval * 1000)) else: # Adjust watchdog for interval. self.watchdog.adjust_for_interval(interval) # Invoke light sleep. # https://docs.micropython.org/en/latest/library/machine.html#machine.sleep # https://docs.micropython.org/en/latest/library/machine.html#machine.lightsleep # # As "machine.sleep" seems to be a noop on Pycom MicroPython, # we will just use the regular "time.sleep" here. # machine.sleep(int(interval * 1000)) machine.idle() if lightsleep: log.info( 'Entering light sleep for {} seconds'.format(interval)) machine.sleep(int(interval * 1000)) else: # Normal wait. log.info('Waiting for {} seconds'.format(interval)) time.sleep(interval)
def periodic_query(): client = mqtt.MQTTClient("beehive", "192.168.1.108") client.connect() print("client connected") def emit(kind, id_, values): print(kind, id_, values) client.publish(b"foobar", b"value", qos=1) while True: machine.sleep(500) for handler in SENSORS.values(): handler(emit) client.publish(b"foobar", b"value", qos=1) client.wait_msg()
def testThread(): begin = utime.ticks_ms() time = utime.ticks_ms() camera.init(1) i = 0 while (time - begin < 3000): if (n < 5): _thread.start_new_thread(cap, ()) else: pass i = i + 1 time = utime.ticks_ms() machine.sleep(500) camera.deinit() print('Took', i, ' pictures')
def sleep(sleep_type, sleep_time=60000): if sleep_type == "deepsleep": print("Putting device into {0} for {1} seconds".format( sleep_type, sleep_time / 1000)) if sleep_time: rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=getattr(machine, sleep_type.upper())) rtc.alarm(rtc.ALARM0, sleep_time) machine.deepsleep() if sleep_type == "idle": machine.idle() if sleep_type == "sleep": machine.sleep() if sleep_type == "wait": time.sleep(sleep_time / 1000)
def capture2s(): os.chdir('webserver') camera.init(1) begin = utime.ticks_ms() time = begin prev = time i=0 machine.sleep(500) #while(time - begin < 2000): #if(time - prev > -1): prev = time i=i+1 name = 'frame'+str(i)+'.jpg' print(name) f = open(name, 'w') buf = camera.capture() f.write(buf) f.close() #time = utime.ticks_ms() camera.deinit()
def test(): import machine import sht3xdis import const scl = machine.Pin(const.SCL, machine.Pin.IN, machine.Pin.PULL_UP) sda = machine.Pin(const.SDA, machine.Pin.IN, machine.Pin.PULL_UP) i2c = machine.SoftI2C(scl=scl, sda=sda, freq=400000) mux = TCA9548A(i2c, reset=13) sensor = sht3xdis.SHT3XDIS(mux.bus(7)) reset = True while True: try: if reset: sensor.reset() sensor.clear() reset = False print(sensor.values) print(sensor.status) machine.sleep(100) except OSError: reset = True
def power_on(self): self._power_on() machine.sleep(100) self.i2c = machine.I2C(1, scl=self.pin_scl, sda=self.pin_sda) machine.sleep(200) self.write_byte(MPU_REG_PWR_MGMT1, 0) machine.sleep(200) self.set_default_range() pass
def callback(line): pass led = LED(RED_LED_ID) pir = Pin(PIR_PIN, Pin.IN) ext = ExtInt(pir, ExtInt.IRQ_RISING, Pin.PULL_NONE, callback) led.on() rtc = RTC() rtc.datetime((2021, 3, 21, 7, 17, 00, 0, 0)) # When connecting LiPo sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.WQXGA2) sensor.skip_frames(time=2000) # Let settings take effect led.off() while True: led.on() t = rtc.datetime() y = str(t[0]) m = '%02d' % t[1] d = '%02d' % t[2] # w = '%d' % t[3] h = '%02d' % t[4] n = '%02d' % t[5] s = '%02d' % t[6] name = 'snapshot_' + y + '-' + m + '-' + d + 'T' + h + '-' + n + '-' + s + 'Z.jpg' sensor.snapshot().save(name) # 0.25 A led.off() machine.sleep() # until external interrupt triggered by PIR, 0.06 A
# Licensed under MIT License, https://github.com/openmv/openmv/blob/master/LICENSE # Button on GND, P4 - triggers external interrupt to wake device up from stop mode. import time, pyb, machine from pyb import Pin, ExtInt, LED BUTTON_PIN = Pin.board.P4 RED_LED_ID = 1 def callback(line): pass def blink(n): while (n > 0): led.on() time.sleep_ms(100) led.off() time.sleep_ms(100) n = n - 1 led = LED(RED_LED_ID) btn = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP) ext = ExtInt(btn, ExtInt.IRQ_FALLING, Pin.PULL_UP, callback) n = 0 while (True): blink(n) # print won't work n = n + 1 # n will be preserved machine.sleep() # IDE will disconnect
def random_sleep(max_sleep): arg = "byteorder='big'" t = int.from_bytes(crypto.getrandbits(32), arg) machine.sleep((1+t%max_sleep)*1000, 0) # wake-up at a random time
def l_sleep(): # noinspection PyArgumentList machine.sleep(10000)
from machine import Pin, sleep from time import sleep_ms pushes = 0 def count_pushes(index): global pushes pushes += 1 pin = Pin(0) pin.irq(count_pushes) while pushes < 5: print(pushes) sleep() while pushes < 10: print(pushes) sleep_ms(1000) print("done")
def start_transmissions(_pkts): global lora global index global lora_sock global active_tx global active_rx global my_slot global proc_gw global AppSKey global succeeded global retrans global dropped global join_start global guard global sack_rcv global msg global sack_bytes airt = int(airtime_calc(my_sf,1,packet_size+2,my_bw_plain)*1000) duty_cycle_limit_slots = math.ceil(100*airt/(airt + 2*guard)) proc_and_switch = 12000 # time for preparing the packet and switch radio mode (us) if (int(MY_ID) == 22 or int(MY_ID) == 34): # fipy nodes switch faster proc_and_switch = 10000 if (my_slot == -1): join_start = time.ticks_us() join_request(my_sf) else: sync() repeats = 0 clock_correct = 0 sync_slot = int(airtime_calc(my_sf,1,sack_bytes+2,my_bw_plain)*1000+3*guard/2) clocks = [sync_slot] print("-----") print("MY SLOT:", my_slot) print("Net size:", index) print("Time on air (ms):", airt/1000) print("Guard time (ms):", guard/1000) print("Duty cycle slots:", duty_cycle_limit_slots) print("Default SACK slot length (ms):", sync_slot/1000) print("Gw processing time (ms):", int(proc_gw/1000)) print("Time after SACK rec (ms):", (time.ticks_us()-sack_rcv)/1000) i = 1 delays = [] delay = 0 (succeeded, retrans, dropped, active_rx, active_tx) = (0, 0, 0, 0.0, 0.0) print("S T A R T") while(i <= _pkts): # stop after pkts # of packets print(i, "----------------------------------------------------") start = time.ticks_us() pycom.rgbled(green) print("starting a new round at (ms):", start/1000) # calculate the time until the sack packet (round_length) if (int(index) > duty_cycle_limit_slots): round_length = math.ceil(int(index)*(airt + 2*guard)) else: round_length = math.ceil(duty_cycle_limit_slots*(airt + 2*guard)) if (len(delays) > 0): delay = sum(delays) / len(delays) round_length += delay + proc_gw # clock delays + gw proc time (us) t = (my_slot*(airt + 2*guard) + guard - proc_and_switch) # sleep time before transmission print("sleep time (ms):", t/1000) pycom.rgbled(off) # time.sleep_us(int(t)) machine.sleep(int(t/1000), 0) # light sleep mode _thread.start_new_thread(generate_msg, ()) pycom.rgbled(red) on_time = time.ticks_us() lora.init(mode=LoRa.LORA, tx_iq=True, region=LoRa.EU868, frequency=freqs[my_sf-5], power_mode=LoRa.TX_ONLY, bandwidth=my_bw, sf=my_sf, tx_power=14) pkg = struct.pack(_LORA_PKG_FORMAT % len(msg), MY_ID, len(msg), msg) print("Sending packet of", len(pkg), "bytes at (ms):", (time.ticks_us()-start)/1000) lora_sock.send(pkg) pycom.rgbled(off) lora.power_mode(LoRa.SLEEP) active_tx += (time.ticks_us() - on_time) t = round_length - (time.ticks_us() - start) if t < 0: t = 0 print("cannot align clock!") print("sleep time after data (s):", t/1e6, "/ clock correction (ms):", clock_correct/1000) # time.sleep_us(int(t)) machine.sleep(int(t/1000), 0) # light sleep mode rec = 0 sack_rcv = 0 clock_correct = 0 acks = "" lora_sock.setblocking(True) lora.init(mode=LoRa.LORA, rx_iq=True, region=LoRa.EU868, frequency=freqs[my_sf-5], power_mode=LoRa.ALWAYS_ON, bandwidth=my_bw, sf=my_sf) sync_start = time.ticks_us() print("started sync slot at (ms):", time.ticks_ms()) pycom.rgbled(white) lora_sock.settimeout(sync_slot/1e6) try: while (rec == 0): machine.idle() sack_rcv = time.ticks_us() recv_pkg = lora_sock.recv(255) if (len(recv_pkg) > 2): recv_pkg_len = recv_pkg[1] recv_pkg_id = recv_pkg[0] if (int(recv_pkg_id) == (my_sf-5)): sack_rcv = time.ticks_us() lora.power_mode(LoRa.SLEEP) active_rx += (time.ticks_us() - sync_start) wt = sack_rcv-sync_start-airtime_calc(my_sf,1,recv_pkg_len,my_bw_plain)*1000 print("Waiting time before receiving SACK (ms):", wt/1000) if (wt != guard) and (i > 1): delays.append(wt-guard) if (len(delays) > 3): delays.pop(0) clock_correct = wt - guard try: dev_id, leng, s_msg = struct.unpack(_LORA_RCV_PKG_FORMAT % recv_pkg_len, recv_pkg) s_msg = str(s_msg)[2:][:-1] (index, proc_gw, acks) = s_msg.split(":") (index, proc_gw) = (int(index), int(proc_gw)*1000) print("SACK received!", s_msg) print(lora.stats()) if (acks != ""): acks = zfill(bin(int(acks, 16))[2:], index) if (acks[my_slot] == "1"): print("ACK!") succeeded += 1 repeats = 0 else: print("I will repeat the last packet") retrans += 1 repeats += 1 i -= 1 if (repeats == 4): print("Packet dropped!") repeats = 0 dropped += 1 retrans -= 1 i += 1 machine.idle() rec = 1 ack_lasted = time.ticks_us()-sync_start if (i == 1): # what if the first packet is dropped. I have to fix this clocks = [ack_lasted] else: clocks.append(ack_lasted) sync_slot = int(sum(clocks)/len(clocks)) if (len(clocks) == 10): clocks = pop(0) print("new sync slot length (ms):", sync_slot/1000) except: print("wrong SACK format!") pass except: if (rec == 0): lora.power_mode(LoRa.SLEEP) active_rx += time.ticks_us() - sync_start print("I will repeat the last packet") retrans += 1 repeats += 1 i -= 1 if (repeats == 4): print("Packet dropped!") print("Synchronisation lost!") repeats = 0 dropped += 1 retrans -= 1 i += 1 pycom.rgbled(red) time.sleep_us(int(round_length-sync_slot-proc_gw)) sync() clock_correct = 0 print("sync slot lasted (ms):", (time.ticks_us()-sync_start)/1000) print("time after SACK (ms):", (time.ticks_us()-sack_rcv)/1000) print("round lasted (ms):", (time.ticks_us()-start)/1000) print("transmitted/delivered/retransmitted/dropped:", i, succeeded, retrans, dropped) print("radio active time (rx/tx) (s):", active_rx/1e6, "/", active_tx/1e6) i += 1 # send out stats print("I'm sending stats") stat_msg = str(i-1)+":"+str(succeeded)+":"+str(retrans)+":"+str(dropped)+":"+str(active_rx/1e6)+":"+str(active_tx/1e6) pkg = struct.pack(_LORA_PKG_FORMAT % len(stat_msg), MY_ID, len(stat_msg), stat_msg) for x in range(3): # send it out 3 times lora.init(mode=LoRa.LORA, tx_iq=True, region=LoRa.EU868, frequency=freqs[7], power_mode=LoRa.TX_ONLY, bandwidth=LoRa.BW_125KHZ, sf=12, tx_power=7) pycom.rgbled(blue) # while (lora.ischannel_free(-90) == False): # print("Channel is busy!") # random_sleep(5) lora_sock.send(pkg) lora.power_mode(LoRa.SLEEP) random_sleep(10) pycom.rgbled(off)
print("entering event loop") sensors.setup() import micropython import umqtt.robust2 as mqtt client = mqtt.MQTTClient("beehive", "192.168.1.108") client.connect() print("client connected") while True: for i in range(10): print("start", i) client.publish(b"foobar", b"start") machine.sleep(100) # for sensor in sensors.SENSORS.values(): # humidity, temp = sensor.raw_values # print(humidity, temp) # client.publish(b"foobar", str(humidity), qos=1) machine.sleep(100) gc.collect() #micropython.mem_info(1) while True: if buttons.wifi_mode() == "ap": nm.run_ap() else: nm.run_sta() poller.poll(timeout=500)
rtc.alarm_cancel() print(rtc_irq_count == 5) rtc_irq_count = 0 rtc.alarm(time=100, repeat=True) time.sleep_ms(1000) rtc.alarm_cancel() print(rtc_irq_count == 10) # deep sleep mode rtc.alarm_cancel() rtc_irq_count = 0 rtc.alarm(time=50, repeat=True) rtc_irq.init(trigger=RTC.ALARM0, handler=alarm_handler, wake=machine.SLEEP | machine.IDLE) while rtc_irq_count < 3: machine.sleep() print(rtc_irq_count == 3) # no repetition rtc.alarm_cancel() rtc_irq_count = 0 rtc.alarm(time=100, repeat=False) time.sleep_ms(250) print(rtc_irq_count == 1) rtc.alarm_cancel() t0 = rtc_ticks_ms(rtc) rtc.alarm(time=500, repeat=False) machine.sleep() t1 = rtc_ticks_ms(rtc) print(abs(t1 - t0 - 500) < 20)
import sensor, image, time, pyb, machine from pyb import Pin, ExtInt sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QVGA) sensor.set_framerate(15) sensor.ioctl(sensor.IOCTL_HIMAX_MD_THRESHOLD, 10) sensor.ioctl(sensor.IOCTL_HIMAX_MD_WINDOW, (0, 0, 320, 240)) sensor.ioctl(sensor.IOCTL_HIMAX_MD_CLEAR) sensor.ioctl(sensor.IOCTL_HIMAX_MD_ENABLE, True) def on_motion(line): pass led = pyb.LED(3) ext = ExtInt(Pin("PC15"), ExtInt.IRQ_RISING, Pin.PULL_DOWN, on_motion) while (True): led.off() sensor.ioctl(sensor.IOCTL_HIMAX_OSC_ENABLE, True) # Switch to internal OSC sensor.ioctl(sensor.IOCTL_HIMAX_MD_CLEAR) # Clear MD flag machine.sleep() # Enter low-power mode, will wake up on MD interrupt. sensor.ioctl(sensor.IOCTL_HIMAX_OSC_ENABLE, False) # Switch back to MCLK led.on() for i in range(0, 60): # Capture a few frames img = sensor.snapshot()
from machine import UART, sleep import sds011 uart = UART(1, baudrate=9600, bits=8, parity=None, stop=1, tx=12, rx=14, rts=-1, cts=-1, txbuf=256, rxbuf=256, timeout=5000, timeout_char=2) dust_sensor = sds011.SDS011(uart) while True: if dust_sensor.read(): print('pm2.5', dust_sensor.pm25, 'pm10', dust_sensor.pm10) else: print('No read') sleep(2000)
# Stop Mode Example # This example demonstrates using the low-power Stop Mode. import time, pyb, machine # Create and init RTC object. rtc = pyb.RTC() # (year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0)) # Print RTC info. print(rtc.datetime()) # Enable RTC interrupts every 5 seconds. rtc.wakeup(5000) # Enter Stop Mode. # Note the IDE will disconnect. machine.sleep()
def th_send(data, id): while True: try: # Pinos 0, 1, 4, 5, 6, 7, 8, 12, 22, 23 reservados para sistema pycom.rgbled(0x0000ff) #Blue print('[PMS] heating up...') PMS = PMS5003ST(TX='P2', RX='P3') utime.sleep(30) print('[PMS] reading...') PMSdata = PMS.PMSReadActive() PMS.deinit() if (PMSdata == False): pycom.rgbled(0xffff00) print('[PMS] failed to read') continue CH2O_PPM = (24.45 * PMSdata[12]) / 30.026 CH2O = str(CH2O_PPM) Temp = str(PMSdata[13]) Humd = str(PMSdata[14]) print('[PMS] finished') print('[MiCS] starting...') MiCS = MiCS6814(SDA='P10', SCL='P11') utime.sleep(1) gases = MiCS.calcAllGases() MiCS.deinit() NO2 = str(gases[1]) #Possui mais gases mas só queremos o NO2 print('[MiCS] finished') print('[MQ] starting...') MQ = MQ131(pin='P16', R0=R0_MQ131) utime.sleep(1) MQvolts = MQ.MQRead() MQPPB = MQ.MQGet_PPB(MQvolts) MQ.deinit() O3 = str(MQPPB) print('[MQ] finished') print('[SEN] starting...') SEN_S = SEN0219_SERIAL(TX='P20', RX='P21') #SEN_S.SEN_Serial_ABCOn() utime.sleep(1) print('[SEN] reading...') SENdata = SEN_S.SEN_Serial_read() SEN_S.deinit() if (SENdata == False): pycom.rgbled(0xffff00) print('[SEN] failed to read') continue SENPPM = (256 * SENdata[2]) + SENdata[3] CO2 = str(SENPPM) print('[SEN] finished') data = '{"keycode": "' + keycode + '","CO2": ' + CO2 + ',"NO2": ' + NO2 + ',"O3": ' + O3 + ',"CH2O": ' + CH2O + ',"Temp": ' + Temp + ',"Humd": ' + Humd + '}' print('[Data] sending...') s.send(data) print("[DATA] saving localy...") f = open('/sd/DataLog.csv', 'a') f.write("\";" + data + "\"\n") f.close() print("[DATA] : " + data) print("[DATA] finished") pycom.rgbled(0x000000) # off machine.sleep(sleep_lenght) except Exception as e: import sys pycom.rgbled(0xff0000) # red print("[Error] ") with open("error.log", "a") as f: sys.print_exception(e, f)
def keys(): global thresh start = utime.time() dim = False dOff = False wait = False while True: try: if t0.read() < thresh and t1.read() < thresh and t2.read( ) < thresh and t3.read() < thresh: party() if t0.read() < thresh: time.sleep(0.02) if t0.read() < thresh: setTone(1) start = utime.time() if wait: machine.freq(40000000) dim = False dOff = False wait = False elif t1.read() < thresh: time.sleep(0.02) if t1.read() < thresh: setTone(2) start = utime.time() if wait: machine.freq(40000000) dim = False dOff = False wait = False elif t2.read() < thresh: time.sleep(0.02) if t2.read() < thresh: setTone(3) start = utime.time() if wait: machine.freq(40000000) dim = False dOff = False wait = False elif t3.read() < thresh: time.sleep(0.02) if t3.read() < thresh: setTone(4) start = utime.time() if wait: machine.freq(40000000) dim = False dOff = False wait = False else: setTone(0) if not pin16: flash() if (utime.time() - start) > 30 and not dim and not wait: print("Dimming") dim = True dimColors() if (utime.time() - start) > 120 and not dOff and not wait: print("Display Off") dOff = True for i in range(10): np[i] = (0, 0, 0) time.sleep(0.02) np.write() #start = utime.time() wait = True machine.freq(20000000) # This bit of code takes the current consumption to ~4mA # but it causes a bit of delay to wake up from sleep # If that annoys you take it out and sleep will be ~14mA if wait: machine.sleep(1000) except ValueError: f = open('silent.txt', 'w') f.write('t') f.close() machine.reset()
def raw_values(self): self._i2c.writeto(self._address, self.MEASUREMENT) machine.sleep(self.MEASUREMENT_TIME) v = self._i2c.readfrom(self._address, 6) humidity, _, temp, _ = ustruct.unpack(">HBHB", v) return humidity, temp
# Mohammad Safeea, 2nd-April-2020 # ESP8266 micropython tutorial # controlling SG90 servomotor using PWM from machine import Pin from machine import PWM from machine import sleep p = Pin(5, 1) # Pin 5 corresponds to PIN D1 on the NODEMCU module servo = PWM(p) servo.freq(100) servo.duty(55) # corresponds to 0 degrees sleep(2) servo.duty(255) # corresponds to 180 degrees sleep(2) # for 15 degrees angle d = 55 + 15 * (200 / 180) # d correpsonds to the duty cycle of 15 degrees d = int(d) servo.duty(d) # motor shaft shall mvoe to approximatly 15 degrees
def go_to_sleep(): print("Going to sleep...") # machine.deepsleep(5000) # machine.deepsleep() machine.sleep()
import camera from machine import UART import machine led = machine.Pin(4, machine.Pin.OUT) machine.sleep(5000) led.on() uart = UART(1, 9600) # init with given baudrate uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters camera.init() buf = camera.capture() camera.deinit() led.off()
import time from network import LoRa import machine loraactive = False if loraactive: LoRa = lora.init() if not loraactive: wifi.set_connect() sensor.defsensor() print("sensor") while True: distance = sensor.getdistance() if not loraactive: wifi.send(distance) print("wifi") else: lora.send(distance) print("LoRa") print("sleeping") machine.sleep(10000, True) print("waking up") # power usage sleep 40 10s, active 70 3s #30,76923076923077 + 233,3333333333333 /13 #20,31558185404339mAh #60h
def l_sleep(ms): machine.sleep(ms)