def party(): """ Show a lot of colors and animation """ print("Party") for i in range(0, np.n): np[i] = (uos.urandom(1)[0], uos.urandom(1)[0], uos.urandom(1)[0]) np.write()
def dual(use_spi=False, soft=True): ssd0 = setup(False, soft) # I2C display ssd1 = setup(True, False) # SPI instance Writer.set_textpos(ssd0, 0, 0) # In case previous tests have altered it wri0 = Writer(ssd0, small, verbose=False) wri0.set_clip(False, False, False) Writer.set_textpos(ssd1, 0, 0) # In case previous tests have altered it wri1 = Writer(ssd1, small, verbose=False) wri1.set_clip(False, False, False) nfields = [] dy = small.height() + 6 col = 15 for n, wri in enumerate((wri0, wri1)): nfields.append([]) y = 2 for txt in ('X:', 'Y:', 'Z:'): Label(wri, y, 0, txt) nfields[n].append(Label(wri, y, col, wri.stringlen('99.99'), True)) y += dy for _ in range(10): for n, wri in enumerate((wri0, wri1)): for field in nfields[n]: value = int.from_bytes(uos.urandom(3),'little')/167772 field.value('{:5.2f}'.format(value)) wri.device.show() utime.sleep(1) for wri in (wri0, wri1): Label(wri, 0, 64, ' DONE ', True) wri.device.show()
def diagnostic(): n = np.n print("Count = ", n) cycle(3, 1000) cycle(10, 100) cycle(10, 50) cycle(10, 30) for j in range(0, 40): for i in range(0, n): r = 10 if uos.urandom(1) <= b'\x30': r = 255 np[(i-1) % n] = (0, 0, 0) np[i] = (r, 10, 10) np.write() time.sleep_ms(30) for j in range(255, 0, -5): for i in range(0, n): np[i] = (j, 0, 0) np.write() time.sleep_ms(10)
def cycle_pallet(t): publish("spin pallet") c = pallet[int(len(pallet) * uos.urandom(1)[0] / 256)] d = (int(c[0] / 5), int(c[1] / 5), int(c[2] / 5)) for j in range(0, t): for on in range(j, lights + j, 44): c = pallet[int(len(pallet) * uos.urandom(1)[0] / 256)] d = (int(c[0] / 5), int(c[1] / 5), int(c[2] / 5)) dim = (on - 1) % lights off = (on - 2) % lights np[on % lights] = c np[dim] = d np[off] = (0, 0, 0) np.write() time.sleep_ms(300)
def _pull_data(self): token = uos.urandom(2) packet = bytes([PROTOCOL_VERSION]) + token + bytes([PULL_DATA]) + ubinascii.unhexlify(self.id) with self.udp_lock: try: self.sock.sendto(packet, self.server_ip) except Exception as ex: self._log('Failed to pull downlink packets from server: {}', ex)
def _push_data(self, data): token = uos.urandom(2) packet = bytes([PROTOCOL_VERSION]) + token + bytes([PUSH_DATA]) + ubinascii.unhexlify(self.id) + data with self.udp_lock: try: self.sock.sendto(packet, self.server_ip) except Exception as ex: self._log('Failed to push uplink packet to server: {}', ex)
def test(): eep = get_eep() sa = 1000 for v in range(256): eep[sa + v] = v for v in range(256): if eep[sa + v] != v: print('Fail at address {} data {} should be {}'.format( sa + v, eep[sa + v], v)) break else: print('Test of byte addressing passed') data = uos.urandom(30) sa = 2000 eep[sa:sa + 30] = data if eep[sa:sa + 30] == data: print('Test of slice readback passed')
def compare_digest(a, b, double_hmac=True, digestmod=b'sha256'): """Test two digests for equality in a more secure way than "==". This employs two main defenses, a double HMAC with a nonce (if available) to blind the timing side channel (to only leak unpredictable information to the side channel) and a constant time comparison. https://paragonie.com/blog/2015/11/preventing-timing-attacks-on-string-comparison-with-double-hmac-strategy The comparison is designed to run in constant time to avoid leaking information through the timing side channel. The constant time nature of this algorithm could be undermined by current or future MicroPython optimizations which is why it is (by default) additionally protected by the double HMAC. It takes as input the output of digest() or hexdigest() of two different HMAC objects, or bytes or a bytearray representing a precalculated digest. """ if not isinstance(a, (bytes, bytearray)) or not isinstance( b, (bytes, bytearray)): raise TypeError( "Expected bytes or bytearray, but got {} and {}".format( type(a).__name__, type(b).__name__)) if len(a) != len(b): raise ValueError( "This method is only for comparing digests of equal length") if double_hmac: try: import uos nonce = uos.urandom(64) except ImportError: double_hmac = False except AttributeError: double_hmac = False if double_hmac: a = new(nonce, a, digestmod).digest() b = new(nonce, b, digestmod).digest() result = 0 for index, byte_value in enumerate(a): result |= byte_value ^ b[index] return result == 0
def fields(use_spi=False, soft=True): ssd = setup(use_spi, soft) # Create a display instance Writer.set_textpos(ssd, 0, 0) # In case previous tests have altered it wri = Writer(ssd, fixed, verbose=False) wri.set_clip(False, False, False) textfield = Label(wri, 0, 2, wri.stringlen('longer')) numfield = Label(wri, 25, 2, wri.stringlen('99.99'), bdcolor=None) countfield = Label(wri, 0, 90, wri.stringlen('1')) n = 1 for s in ('short', 'longer', '1', ''): textfield.value(s) numfield.value('{:5.2f}'.format(int.from_bytes(uos.urandom(2),'little')/1000)) countfield.value('{:1d}'.format(n)) n += 1 refresh(ssd) utime.sleep(2) textfield.value('Done', True) refresh(ssd)
def main(): eep = get_device() try: uos.mount(eep, directory) except OSError: # Already mounted pass for n in range(128): length = fcreate(n) print('Created', n, length) print('Created files', files) check_all() for _ in range(100): for x in range(5): # Rewrite 5 files with new lengths n = int.from_bytes(uos.urandom(1), 'little') & 0x7f length = fcreate(n) print('Rewrote', n, length) check_all() remove_all()
def render(self, frame, dropped_frames, fps): """ Render the scene. This method is called by the render loop with the current frame number, the number of dropped frames since the previous invocation and the requested frames per second (FPS). """ display = self.display get_pixel = display.get_pixel put_pixel = display.put_pixel intensity = self.intensity width = display.columns max_y = display.stride - 1 # Fire source b = intensity >> 1 for x in range(display.columns): put_pixel(x, max_y, intensity, intensity, b) # Spread fire for y in range(max_y): for x in range(width): # Cool previous pixel r, g, b = display.get_pixel(x, y) if r or g or b: r -= 1 g -= 1 b >>= 1 put_pixel(x, y, max(r, 0), max(g, 0), b) # Spread heat from below r, g, b = get_pixel(x, y+1) spread = (urandom(1)[0]&3) - 1 r -= spread g -= 1 b >>= 2 put_pixel(x+spread, y, max(r, 0), max(g, 0), b) display.render() self.remaining_frames -= 1 if not self.remaining_frames: return False return True
def compare_digest(a, b, double_hmac=True, digestmod=b'sha256'): """Test two digests for equality in a more secure way than "==". This employs two main defenses, a double HMAC with a nonce (if available) to blind the timing side channel (to only leak unpredictable information to the side channel) and a constant time comparison. https://paragonie.com/blog/2015/11/preventing-timing-attacks-on-string-comparison-with-double-hmac-strategy The comparison is designed to run in constant time to avoid leaking information through the timing side channel. The constant time nature of this algorithm could be undermined by current or future MicroPython optimizations which is why it is (by default) additionally protected by the double HMAC. It takes as input the output of digest() or hexdigest() of two different HMAC objects, or bytes or a bytearray representing a precalculated digest. """ if not isinstance(a, (bytes, bytearray)) or not isinstance(b, (bytes, bytearray)): raise TypeError("Expected bytes or bytearray, but got {} and {}".format(type(a).__name__, type(b).__name__)) if len(a) != len(b): raise ValueError("This method is only for comparing digests of equal length") if double_hmac: try: import uos nonce = uos.urandom(64) del uos except ImportError: double_hmac = False except AttributeError: double_hmac = False if double_hmac: a = new(nonce, a, digestmod).digest() b = new(nonce, b, digestmod).digest() result = 0 for index, byte_value in enumerate(a): result |= byte_value ^ b[index] return result == 0
def flash_test(format=False): eep = get_flash() if format: uos.VfsLfs2.mkfs(eep) try: uos.mount(eep, '/fl_ext') except OSError: # Already mounted pass for n in range(128): length = fcreate(n) print('Created', n, length) print('Created files', files) check_all() for _ in range(100): for x in range(5): # Rewrite 5 files with new lengths n = int.from_bytes(uos.urandom(1), 'little') & 0x7f length = fcreate(n) print('Rewrote', n, length) check_all() remove_all()
def meter(): print('meter') refresh(ssd, True) # Clear any prior image m = Meter(wri, 5, 2, height=45, divisions=4, ptcolor=YELLOW, label='level', style=Meter.BAR, legends=('0.0', '0.5', '1.0')) l = LED(wri, 5, 40, bdcolor=YELLOW, label='over') steps = 10 for _ in range(steps): v = int.from_bytes(uos.urandom(3), 'little') / 16777216 m.value(v) l.color(GREEN if v < 0.5 else RED) refresh(ssd) utime.sleep(1) refresh(ssd)
def send_measurement(sensor, address): sensor.measure() temperature = sensor.temperature() humidity = sensor.humidity() print(temperature, humidity) measurement_id = uos.urandom(16) for i in range(3): s = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) s.sendto( ujson.dumps({ "sensor_id": ubinascii.hexlify(machine.unique_id()), "sensor_type": "ESP32/DHT22", "sensor_time": utime.time(), "measurement_id": ubinascii.hexlify(measurement_id), "measurement_data": { "temperature": temperature, "humidity": humidity, } }), address) utime.sleep(0.1)
def randint(a, b): """Returns a random integer bet a and b (not included). Args: a: starting integer b: ending integer (not included) Returns: int """ assert (b > a) r = (b - a) # range bits = math.ceil( math.log(r) / math.log(2)) + 7 + 8 # 8 more bits to make posibility more even. num_bytes = int(bits / 8) random_bytes = uos.urandom(num_bytes) s = 0 # sum for b in random_bytes: s = s * 256 + b result = (s % r) + a return result
def do_connect(): wlan = network.WLAN(network.STA_IF) wlan.active(True) attempt = 1 wifis = [] with open('wifi.txt') as f: wifis = f.readlines() print(wifis) wifi = lambda: int(uos.urandom(1)[0]) % len(wifis) if not wlan.isconnected(): print('connecting to network...') wlan.connect(*tuple(map(lambda x: x.strip(), wifis[wifi()].split()))) while not wlan.isconnected(): time.sleep_ms(350) attempt += 1 if attempt > 25: attempt = 0 wlan.connect( *tuple(map(lambda x: x.strip(), wifis[wifi()].split()))) print('network config:', wlan.ifconfig())
def kP(self, k, P): """scalar point multiplication k*P""" if k == 0: return curve.Infinity else: zp = int.from_bytes(urandom(self.bytelen_p - 1), 'big', False) | 1 xp = P.x * pow(zp, 2, self.p) % self.p yp = P.y * pow(zp, 3, self.p) % self.p while k & 1 == 0: xp, yp, zp = self.double(xp, yp, zp) k >>= 1 x, y, z = xp, yp, zp k >>= 1 while k > 0: xp, yp, zp = self.double(xp, yp, zp) if k & 1 == 1: if z == 0: x, y, z = xp, yp, zp else: x, y, z = self.add(x, y, z, xp, yp, zp) k >>= 1 return self.jacobian2affin(x, y, z)
def initial_setup(): # noinspection PyUnresolvedReferences import ubinascii print('INITIAL SETUP') ssid = input('WIFI SSID: ') passwd = input('WIFI PASS: '******'credentials.py', 'w') as fp: # fp.write('"""WLAN credentials secrets, generated by setup"""\n\n'.format(ssid)) fp.write('WLAN_SSID: str = \'{}\'\n'.format(ssid)) fp.write('WLAN_PASS: str = \'{}\'\n'.format(passwd)) fp.flush() print('Credentials saved\n') device_id = input('Device ID (empty for random): ') if not device_id: device_id = ubinascii.hexlify(uos.urandom(8)) with open('device_id', 'w') as fp: fp.write(device_id) fp.flush() print('New device_id={} saved\n'.format(device_id)) machine.reset()
def generate_puzzle(self): """Generate a random solution and derive the hints based on that generated solution.""" # generate random solution grid for i in range(GRID_SIZE_X): for j in range(GRID_SIZE_Y): random = ord(uos.urandom(1)) % 2 self.SOLUTION_GRID[i][j] = random # column hints for x in range(GRID_SIZE_X): self.HINTS_COLUMNS[x] = [] group_size = 0 for y in range(GRID_SIZE_Y): cell = self.SOLUTION_GRID[x][y] if cell == FILLED: group_size += 1 elif cell == EMPTY and group_size > 0: self.HINTS_COLUMNS[x].append(group_size) group_size = 0 # all rows processed if len(self.HINTS_COLUMNS[x]) == 0 or group_size > 0: self.HINTS_COLUMNS[x].append(group_size) # row hints for y in range(GRID_SIZE_Y): self.HINTS_ROWS[y] = [] group_size = 0 for x in range(GRID_SIZE_X): cell = self.SOLUTION_GRID[x][y] if cell == FILLED: group_size += 1 elif cell == EMPTY and group_size > 0: self.HINTS_ROWS[y].append(group_size) group_size = 0 # all columns processed if len(self.HINTS_ROWS[y]) == 0 or group_size > 0: self.HINTS_ROWS[y].append(group_size)
def prepare_channels_eu868(lora, channel, data_rate): EU868_FREQUENCIES = [ { "chan": 1, "fq": "865100000" }, { "chan": 2, "fq": "865300000" }, { "chan": 3, "fq": "865500000" }, { "chan": 4, "fq": "865700000" }, { "chan": 5, "fq": "865900000" }, { "chan": 6, "fq": "866100000" }, { "chan": 7, "fq": "866300000" }, { "chan": 8, "fq": "866500000" }, { "chan": 9, "fq": "867100000" }, { "chan": 10, "fq": "867300000" }, { "chan": 11, "fq": "867500000" }, { "chan": 12, "fq": "867700000" }, { "chan": 13, "fq": "867900000" }, { "chan": 14, "fq": "868100000" }, { "chan": 15, "fq": "868300000" }, { "chan": 16, "fq": "868500000" }, ] if not channel in range(0, 17): raise RuntimeError("channels should be in 1-8 for EU868") if channel == 0: import uos channel = (struct.unpack('B',uos.urandom(1))[0] % 7) + 1 for i in range(0, 16): lora.remove_channel(i) upstream = (item for item in EU868_FREQUENCIES if item["chan"] == channel).__next__() # set default channels frequency lora.add_channel(int(upstream.get('chan')), frequency=int(upstream.get('fq')), dr_min=0, dr_max=data_rate) return lora
def multi_fields(t): print('multi_fields') refresh(ssd, True) # Clear any prior image nfields = [] dy = wri.height + 6 y = 2 col = 15 width = wri.stringlen('99.99') for txt in ('X:', 'Y:', 'Z:'): Label(wri, y, 0, txt) # Use wri default colors nfields.append(Label(wri, y, col, width, bdcolor=None)) # Specify a border, color TBD y += dy end = utime.ticks_add(utime.ticks_ms(), t * 1000) while utime.ticks_diff(end, utime.ticks_ms()) > 0: for field in nfields: value = int.from_bytes(uos.urandom(3),'little')/167772 overrange = None if value < 70 else YELLOW if value < 90 else RED field.value('{:5.2f}'.format(value), fgcolor = overrange, bdcolor = overrange) refresh(ssd) utime.sleep(1) Label(wri, 0, 64, ' OK ', True, fgcolor = RED) refresh(ssd) utime.sleep(1)
def multi_fields(use_spi=False, soft=True): ssd = setup(use_spi, soft) # Create a display instance Writer.set_textpos(ssd, 0, 0) # In case previous tests have altered it wri = Writer(ssd, small, verbose=False) wri.set_clip(False, False, False) nfields = [] dy = small.height() + 6 y = 2 col = 15 width = wri.stringlen('99.99') for txt in ('X:', 'Y:', 'Z:'): Label(wri, y, 0, txt) nfields.append(Label(wri, y, col, width, bdcolor=None)) # Draw border y += dy for _ in range(10): for field in nfields: value = int.from_bytes(uos.urandom(3),'little')/167772 field.value('{:5.2f}'.format(value)) refresh(ssd) utime.sleep(1) Label(wri, 0, 64, ' DONE ', True) refresh(ssd)
def send_msg(msg): global msg_id retry = _RETRY_COUNT while(retry > 0 and not retry == -1): retry -= 1 pkg = struct.pack(_LORA_PKG_FORMAT % len(msg), _DEVICE_ID, len(msg), msg_id, msg) lora_sock.send(pkg) # Wait for the response from the server start_time = time.ticks_ms() while(not check_ack_time(start_time)): recv_ack = lora_sock.recv(256) # If a message of the size of the ackowledge message is received if(len(recv_ack) == 4): device_id, pkg_len, recv_msg_id, status = struct.unpack(_LORA_PKG_ACK_FORMAT, recv_ack) if(device_id == _DEVICE_ID and recv_msg_id == msg_id): if(status == 200): return True else: return False time.sleep_ms(urandom(1)[0] << 2) return False
wifi.connect(wifiSSID, wifiPassword) # # wait until the ESP8266 is connected to the WiFi network # maxAttempts = 20 attemptCount = 0 while not wifi.isconnected() and attemptCount < maxAttempts: attemptCount += 1 utime.sleep(1) print('did not connect...trying again') # # create a random MQTT clientID # randomNum = int.from_bytes(uos.urandom(3), 'little') myMqttClient = bytes("client_" + str(randomNum), 'utf-8') # connect to Thingspeak MQTT broker # connection uses unsecure TCP (port 1883) # # Steps to change to a secure connection (encrypted) using TLS # a) change port below to "port=8883 # b) add parameter "ssl=True" # NOTE: TLS uses about 9k bytes of the heap. That is a lot. # (about 1/4 of the micropython heap on the ESP8266 platform) thingspeakUrl = b"mqtt.thingspeak.com" thingspeakUserId = b"gfavalessaf" # EDIT - enter Thingspeak User ID thingspeakMqttApiKey = b"XO5VTN0FLOTMA3DV" # EDIT - enter Thingspeak MQTT API Key
def get_raw_battery_value(): return 1000 + (int.from_bytes(urandom(2), "big") % 20)
23:'MahnaMahna', 24:'LeisureSuit', 25:'MissionImp' } def play_tone(freq, msec): # print('freq = {:6.1f} msec = {:6.1f}'.format(freq, msec)) # print("Freq: %6.1f, duration: %6.1f"%(freq,msec)) if freq > 0: speaker.freq(int(freq)) # Set frequency speaker.duty(512) # 50% duty cycle sleep_ms(int(msec)) # Play for a number of msec speaker.duty(0) # Stop playing sleep_ms(50) # Delay 50 ms between notes song_numbers = os.urandom(100) cnt = 0 print("Push the button to sound the door bell") while True: if btn.value() == PUSHED: song_nr = int(int(song_numbers[cnt])/10.21) +1 songName = songList.get(song_nr) print("Play song ",songName) sleep_ms(20) # debounce switch # play the song tune = RTTTL(songs.find(songName)) for freq, msec in tune.notes(): play_tone(freq, msec) cnt += 1 if cnt > 99: songs = os.urandom(100)
__all__ = ("randInt", "randFloat") try: import ulab as np from uos import urandom randInt = lambda: int.from_bytes(urandom(1), "little") randFloat = lambda: int.from_bytes(urandom(4), "little") / 2**32 except ImportError: import numpy as np import random randInt = lambda: random.randrange(2**8) randFloat = lambda: random.uniform(0.0, 1.0) def shuffle(iterable): return [xx[1] for xx in sorted([(randFloat(), item) for item in iterable])]
VERSION_FILE = "OTA_VERSION.txt" # timing STANDARD_DURATION_S = 1 BLINKING_DURATION_S = 60 WAIT_FOR_TUNING_S = 30 WATCHDOG_TIMEOUT_MS = 6 * 60 * 1000 MAX_INACTIVITY_TIME_S = 60 * 60 # min * sec FIRST_INTERVAL_INACTIVITY_S = MAX_INACTIVITY_TIME_S / 16 # =225 sec EXP_BACKOFF_INACTIVITY = 2 OVERSHOOT_DETECTION_PAUSE_S = 60 # sec RESTART_OFFSET_TIME_S = 24 * 60 * 60 + ( int.from_bytes(os.urandom(2), "big") % 0x0FFF) # define restart time = 1 day + (0 .. 4095) seconds # setup the logging log = logging.getLogger() log.info("RESTART IN: {} s".format(RESTART_OFFSET_TIME_S)) # get the reason for reset in readable form RESET_REASON = translate_reset_cause(machine.reset_cause()) ################################################################################ # State Machine class StateMachine(object): def __init__(self):
def rand(self): return int.from_bytes(uos.urandom(4), 'little')
def rand(): return int.from_bytes(uos.urandom(1), 'little')
def generate_randomID(): global SessionID SessionID = uos.urandom(16) global topic1 client.publish(topic1, SessionID)
import gc import uos import time print("Mem Pre Import:", gc.mem_free()) import at24cxx print("Mem Pre Collect:", gc.mem_free()) gc.collect() print("Mem Post Collect:", gc.mem_free()) i2c = machine.I2C(machine.Pin(12), machine.Pin(13), freq=100000) eeprom = at24cxx.AT24CXX(i2c) rnd = bytearray(uos.urandom(10)) eeprom.write(0, rnd) time.sleep(.1) print(eeprom.read(0, 10) == rnd) eeprom.write_address(1) time.sleep(.1) print(eeprom.read_sequential(4) == rnd[1:5]) rnd_ = uos.urandom(1)[0] eeprom.write_byte(0, rnd_) time.sleep(.1) rnd[0] = rnd_ print(eeprom.read(0, 10) == rnd)
request.close() a_x = 0 a_y = 0 a_z = 0 temp = 0 tim2 = Timer(2) tim2.init(period=3000, mode=Timer.PERIODIC, callback=lambda t: ifttt_upload_data(a_x, a_y, a_z, temp)) client.subscribe(topic2) while True: SessionID = uos.urandom(16) client.publish(topic1, SessionID) while waiting_msg: client.check_msg() waiting_msg = 1 crypt_data = crypt.CryptAes(SessionID) verifying_hmac = crypt_data.verify_hmac(sensor_hmacdata) if verifying_hmac != b'HMAC Authenticated': client.publish(topic3, verifying_hmac) else: decrypt_msg, decrypted_data = crypt_data.decrypt(sensor_hmacdata) a_x = decrypted_data['a_x'] a_y = decrypted_data['a_y']
#fb.text('Hello World',30,0,black) #fb.pixel(30, 10, black) #fb.hline(30, 30, 10, black) #fb.vline(30, 50, 10, black) #fb.line(30, 70, 40, 80, black) #fb.rect(30, 90, 10, 10, black) fb.fill_rect(1, 0, 8, 8, black) from uos import urandom import color_name for row in range(0, 25): fb.text(str('{:02d}'.format(row)), 10, row * 8, black) fb.rect(1, row * 8, 8, 8, black) rand_color = urandom(3) rand_color_name = color_name.ColorNames.findNearestWebColorName(rand_color) fb.text(rand_color_name, 30, row * 8, black) print(list(rand_color), rand_color_name) e.set_frame_memory(buf, x, y, w, h) e.display_frame() ## NEW Landscape mode ''' h = 200; w = 200 # e-paper heigth and width. buf_black = bytearray(w * h // 8) # used by frame buffer (landscape) buf_epaper_black = bytearray(w * h // 8) # used to display on e-paper after bytes have been #import framebuf
display.text('Hello World', 0, 0, 15) display.show() display.scroll(0, 16) # corner pixels display.fill(0) display.pixel(0, 0, 15) display.pixel(0, 95, 15) display.pixel(95, 95, 15) display.pixel(95, 0, 15) display.show() # random pixels (slow) import uos for i in range(0, 256): x = uos.urandom(1)[0] // 2 y = uos.urandom(1)[0] // 2 display.pixel(x, y, 15) display.show() # invert greyscale lookup table display.invert(True) display.invert(False) # greyscale lookup display.fill(0) for r in range(0, 16): display.framebuf.fill_rect(0, r * 6, 96, 6, r) display.show() # more dark shades
# Untitled - By: Brady - Tue Sep 3 2019 import uos import pyb import sensor, time, image print("here1") dir = uos.urandom(3) print(dir) dir2 = uos.getcwd() print(dir2) print("here2") #uos.mkdir("/Path") print("here3") print("here33") dir2 = uos.getcwd() print(dir2) print("here4") uos.chdir("/") snap_img = image.Image("snapshot-384550201.pgm").mask_ellipse() d0 = snap_img.find_lbp((0, 0, snap_img.width(), snap_img.height())) lbp_list = [] name_list = [] uos.chdir("/Faces") for filename in uos.listdir("/Faces"): if filename.endswith(".pgm") : img = None
import machine import uos import sh1106 import utime from machine import I2C, Pin, ADC adc = machine.ADC(0) i2c = I2C(scl=Pin(12), sda=Pin(14)) oled = sh1106.SH1106_I2C(128, 64, i2c) while True: for _ in range(500): x = int(uos.urandom(1)[0] / 2) y = int(uos.urandom(1)[0] / 4) oled.pixel(x, y, 1) oled.show() utime.sleep_ms(200) oled.fill(0)