def run(): # some SD cards won't work in 4-bit mode unless freq() is explicitely set freq(240 * 1000 * 1000) # 80/160/240 MHz, faster CPU = faster SD card #sd=SDCard(slot=3) # 1-bit mode sd = SDCard() # 4-bit mode mount(sd, "/sd") print(listdir("/sd")) f = open("/sd/long_file.bin", "rb") # any 1-10 MB long file b = bytearray(16 * 1024) i = 0 t1 = ticks_ms() while f.readinto(b): i += 1 t2 = ticks_ms() print("%d KB in %d ms => %d KB/s file read" % (i * len(b) // 1024, t2 - t1, 1000 * i * len(b) // 1024 // (t2 - t1))) f.close() umount("/sd") i = 0 t1 = ticks_ms() while i < 256: sd.readblocks(i, b) i += 1 t2 = ticks_ms() print("%d KB in %d ms => %d KB/s raw sector read" % (i * len(b) // 1024, t2 - t1, 1000 * i * len(b) // 1024 // (t2 - t1))) sd.deinit()
def wipe(): """ Blocks map in disco board 0: MBR 1 - 255: reserved 256 - 447: internal flash 448 - 33215: QSPI """ # delete files normally in simulator try: delete_recursively(fpath("/flash")) delete_recursively(fpath("/qspi")) except: pass # on real hardware overwrite flash with random data if not simulator: os.umount("/flash") os.umount("/qspi") f = pyb.Flash() block_size = f.ioctl(5, None) # wipe internal flash with random bytes for i in range(256, 450): b = os.urandom(block_size) f.writeblocks(i, b) del b gc.collect() # mpy will reformat fs on reboot reboot()
def wipe_flash_filesystem(): # erase and re-format the flash filesystem (/flash/) import ckcc, pyb from main import dis, settings dis.fullscreen('Erasing...') os.umount('/flash') # from extmod/vfs.h BP_IOCTL_SEC_COUNT = (4) BP_IOCTL_SEC_SIZE = (5) # block-level erase fl = pyb.Flash() bsize = fl.ioctl(BP_IOCTL_SEC_SIZE, 0) assert bsize == 512 bcount = fl.ioctl(BP_IOCTL_SEC_COUNT, 0) blk = bytearray(bsize) ckcc.rng_bytes(blk) # trickiness: actual flash blocks are offset by 0x100 (FLASH_PART1_START_BLOCK) # so fake MBR can be inserted. Count also inflated by 2X, but not from ioctl above. for n in range(bcount): fl.writeblocks(n + 0x100, blk) ckcc.rng_bytes(blk) dis.progress_bar_show(n * 2 / bcount) # rebuild and mount /flash dis.fullscreen('Rebuilding...') ckcc.wipe_fs() # re-store settings settings.save()
def wipe_microsd_card(): import ckcc, pyb from main import dis try: os.umount('/sd') except: pass sd = pyb.SDCard() assert sd if not sd.present(): return # power cycle so card details (like size) are re-read from current card sd.power(0) sd.power(1) dis.fullscreen('Part Erase...') cutoff = 1024 # arbitrary blk = bytearray(512) for bnum in range(cutoff): ckcc.rng_bytes(blk) sd.writeblocks(bnum, blk) dis.progress_bar_show(bnum / cutoff) dis.fullscreen('Formating...') # remount, with newfs option os.mount(sd, '/sd', readonly=0, mkfs=1)
def quick_test_hw(hw): _logger.info("Starting quick self test...") pycom_util.reset_rgbled() _logger.info("Starting hardware quick check") chrono = machine.Timer.Chrono() chrono.start() with CheckStep(FLAG_MOSFET_PIN, suppress_exception=True): if hw.mosfet_pin: _logger.info("Mosfet pin state: %s", hw.mosfet_pin()) wdt.feed() with CheckStep(FLAG_SD_CARD, suppress_exception=True): import os mountpoint = "/co2_sd_card_test" os.mount(hw.sdcard, mountpoint) contents = os.listdir(mountpoint) os.umount(mountpoint) _logger.info("SD card OK. Contents: %s", contents) wdt.feed() with CheckStep(FLAG_ERTC, suppress_exception=True): ertc = hw.ertc time_tuple = ertc.get_time() _logger.info("External RTC ok. Current time: %s", time_tuple) wdt.feed() with CheckStep(FLAG_CO2, suppress_exception=True): import explorir co2 = hw.co2 co2.set_mode(explorir.MODE_POLLING) reading = co2.read_co2() _logger.info("CO2 sensor ok. Current level: %d ppm", reading) wdt.feed() with CheckStep(FLAG_ETEMP, suppress_exception=True): etemp = hw.etemp _logger.debug("Starting external temp read. Can take up to 750ms.") etemp.start_conversion() chrono.reset() while True: reading = etemp.read_temp_async() if reading: break if chrono.read_ms() > 1000: raise TimeoutError( "Timeout reading external temp sensor after %d ms" % chrono.read_ms()) _logger.info("External temp sensor ok. Current temp: %s C", reading) wdt.feed() show_boot_flags() _logger.info("Failures after quick hardware check: 0x%04x", failures) display_errors_led() wdt.feed() pycom.rgbled(0x0)
def sdtest2(): spi = machine.SPI(1) spi.init() # Ensure right baudrate sd = sdcard.SDCard(spi, machine.Pin(15)) # Compatible with PCB # vfs = os.VfsLfs2(sd) vfs = os.VfsFat(sd) os.mount(vfs, "/fc") print("Filesystem check") print(os.listdir("/fc")) line = "abcdefghijklmnopqrstuvwxyz\n" lines = line * 200 # 5400 chars short = "1234567890\n" fn = "/fc/rats.txt" print() print("Multiple block read/write") with open(fn, "w") as f: n = f.write(lines) print(n, "bytes written") n = f.write(short) print(n, "bytes written") n = f.write(lines) print(n, "bytes written") with open(fn, "r") as f: result1 = f.read() print(len(result1), "bytes read") fn = "/fc/rats1.txt" print() print("Single block read/write") with open(fn, "w") as f: n = f.write(short) # one block print(n, "bytes written") with open(fn, "r") as f: result2 = f.read() print(len(result2), "bytes read") os.umount("/fc") print() print("Verifying data read back") success = True if result1 == "".join((lines, short, lines)): print("Large file Pass") else: print("Large file Fail") success = False if result2 == short: print("Small file Pass") else: print("Small file Fail") success = False print() print("Tests", "passed" if success else "failed")
def sdtest(): spi = machine.SPI(1) spi.init() # Ensure right baudrate sd = sdcard.SDCard(spi, machine.Pin.board.X21) # Compatible with PCB vfs = os.VfsFat(sd) os.mount(vfs, '/fc') print('Filesystem check') print(os.listdir('/fc')) line = 'abcdefghijklmnopqrstuvwxyz\n' lines = line * 200 # 5400 chars short = '1234567890\n' fn = '/fc/rats.txt' print() print('Multiple block read/write') with open(fn,'w') as f: n = f.write(lines) print(n, 'bytes written') n = f.write(short) print(n, 'bytes written') n = f.write(lines) print(n, 'bytes written') with open(fn,'r') as f: result1 = f.read() print(len(result1), 'bytes read') fn = '/fc/rats1.txt' print() print('Single block read/write') with open(fn,'w') as f: n = f.write(short) # one block print(n, 'bytes written') with open(fn,'r') as f: result2 = f.read() print(len(result2), 'bytes read') os.umount('/fc') print() print('Verifying data read back') success = True if result1 == ''.join((lines, short, lines)): print('Large file Pass') else: print('Large file Fail') success = False if result2 == short: print('Small file Pass') else: print('Small file Fail') success = False print() print('Tests', 'passed' if success else 'failed')
def unmount_sdcard() -> bool: """Unmounts SD card""" # sync file system before unmounting if not is_sd_present(): raise RuntimeError("SD card is not present") if sdcard is not None: os.sync() os.umount("/sd") sdcard.power(False) sdled.off()
def fs_unuse_sd(): global sd_vfs_fat global sd_mnt_point if sd_vfs_fat == None: print("SD not used") return os.umount(sd_mnt_point) sd_vfs_fat = None print("SD unmounted")
def recover(self): self.active = False try: os.umount('/sd') except: pass # important: turn off power so touch can work again sd = pyb.SDCard() sd.power(0)
def recover(self): # done using the microSD -- unpower it self.active_led.off() self.active = False try: os.umount('/sd') except: pass # important: turn off power so touch can work again sd = pyb.SDCard() sd.power(0)
def change_file(self): oldselected = self.fb_selected - self.fb_topitem self.fb_selected = self.fb_cursor try: filename = self.fullpath(self.direntries[self.fb_cursor][0]) except: filename = False self.fb_selected = -1 self.show_dir_line(oldselected) self.show_dir_line(self.fb_cursor - self.fb_topitem) if filename: if filename.endswith(".bit"): self.spi_request.irq(handler=None) self.timer.deinit() self.enable[0] = 0 self.osd_enable(0) self.spi.deinit() tap = ecp5.ecp5() tap.prog_stream(open(filename, "rb"), blocksize=1024) if filename.endswith("_sd.bit"): os.umount("/sd") for i in bytearray([2, 4, 12, 13, 14, 15]): p = Pin(i, Pin.IN) a = p.value() del p, a result = tap.prog_close() del tap gc.collect() #os.mount(SDCard(slot=3),"/sd") # BUG, won't work self.init_spi() # because of ecp5.prog() spi.deinit() self.spi_request.irq(trigger=Pin.IRQ_FALLING, handler=self.irq_handler_ref) self.irq_handler(0) # handle stuck IRQ if filename.endswith(".z80"): self.enable[0] = 0 self.osd_enable(0) import ld_zxspectrum s = ld_zxspectrum.ld_zxspectrum(self.spi, self.cs) s.loadz80(filename) del s gc.collect() if filename.endswith(".nes"): import ld_zxspectrum s = ld_zxspectrum.ld_zxspectrum(self.spi, self.cs) s.ctrl(1) s.ctrl(0) s.load_stream(open(filename, "rb"), addr=0, maxlen=0x101000) del s gc.collect() self.enable[0] = 0 self.osd_enable(0)
def stop(self): if self.mounted: self.mounted = False try: os.umount(self.sd_path) except Exception as e: sys.print_exception(e) print('sd umount failure') if self.inited: try: self.sdcard.deinit() except Exception as e: sys.print_exception(e) print('sd deinit failure')
def recover(self): # done using the microSD -- unpower it from main import numpad self.active = False try: os.umount('/sd') except: pass # important: turn off power so touch can work again sd = pyb.SDCard() sd.power(0) numpad.start()
def test_format_sd(): sd_mnt_point = "/sd" spi = machine.SPI(1, sck=machine.Pin(10), mosi=machine.Pin(11), miso=machine.Pin(12), baudrate=10000) cs = machine.Pin(15) sd = sdcard.SDCard(spi, cs) os.VfsFat.mkfs(sd) sd_vfs_fat = os.VfsFat(sd) os.mount(sd_vfs_fat, sd_mnt_point) print("SD mounted") os.umount(sd_mnt_point) print("SD unmounted")
def create_loopback_devices(osds: int) -> None: assert osds size = (5 * osds) + 1 print(f'Using {size}GB of data to store osds') # loop_dev = run_shell_command('sudo losetup -f') loop_dev = '/dev/loop111' run_shell_command(f'sudo rm -f {loop_dev}') run_shell_command(f'sudo mknod -m 0777 {loop_dev} b 7 111') # cleanup last call cleanup() if os.path.ismount(loop_dev): os.umount(loop_dev) loop_devices = json.loads( run_shell_command('losetup -l -J', expect_error=True)) for dev in loop_devices['loopdevices']: if dev['name'] == loop_dev: run_shell_command(f'sudo losetup -d {loop_dev}') if not os.path.exists('./loop-images'): os.mkdir('loop-images') remove_loop_img() loop_image = Config.get('loop_img') run_shell_command( f'sudo dd if=/dev/zero of={loop_image} bs=1 count=0 seek={size}G') run_shell_command(f'sudo losetup {loop_dev} {loop_image}') run_shell_command(f'sudo pvcreate {loop_dev} ') run_shell_command(f'sudo vgcreate vg1 {loop_dev}') p = int( 100 / osds ) # FIXME: 100 osds is the maximum because of lvcreate pct (it doesn't seem to work with lots more decimals) for i in range(osds): run_shell_command('sudo vgchange --refresh') run_shell_command(f'sudo lvcreate -l {p}%VG --name lv{i} vg1') # FIXME: use /dev/vg1/lv* links as it is less hacky (there could be unrelated dm devices) run_shell_command(f'sudo chmod 777 /dev/dm-*') return loop_dev
def sdtest1(): spi = machine.SPI(1, sck=machine.Pin(10), mosi=machine.Pin(11), miso=machine.Pin(12)) spi = machine.SPI(1) cs = machine.Pin(15) sd = sdcard.SDCard(spi, cs) vfs = os.VfsFat(sd) os.mount(vfs, '/sd') os.mkdir('/sd/sd2') os.chdir('/sd/sd2') with open("pico2.txt", "a") as file: for i in range(10): file.write(str(i)+"2. Hello, world!\r\n") os.chdir('/') os.umount("/sd")
def create_loopback_devices(osds: int) -> None: assert osds size = (5 * osds) + 1 print(f'Using {size}GB of data to store osds') avail_loop = run_shell_command('sudo losetup -f') base_name = os.path.basename(avail_loop) # create loop if we cannot find it if not os.path.exists(avail_loop): num_loops = int( run_shell_command('lsmod | grep loop | awk \'{print $3}\'')) num_loops += 1 run_shell_command(f'mknod {avail_loop} b 7 {num_loops}') if os.path.ismount(avail_loop): os.umount(avail_loop) loop_devices = json.loads( run_shell_command(f'losetup -l -J', expect_error=True)) for dev in loop_devices['loopdevices']: if dev['name'] == avail_loop: run_shell_command(f'sudo losetup -d {avail_loop}') if not os.path.exists('./loop-images'): os.mkdir('loop-images') remove_loop_img() loop_image = Config.get('loop_img') run_shell_command( f'sudo dd if=/dev/zero of={loop_image} bs=1 count=0 seek={size}G') run_shell_command(f'sudo losetup {avail_loop} {loop_image}') # cleanup last call cleanup() run_shell_command(f'sudo pvcreate {avail_loop} ') run_shell_command(f'sudo vgcreate vg1 {avail_loop}') p = int(100 / osds) for i in range(osds): run_shell_command('sudo vgchange --refresh') run_shell_command(f'sudo lvcreate -l {p}%VG --name lv{i} vg1')
def wipe_microsd_card(): # Erase and re-format SD card. Not secure erase, because that is too slow. import callgate import pyb from common import dis try: os.umount('/sd') except: pass sd = pyb.SDCard() assert sd if not sd.present(): return # power cycle so card details (like size) are re-read from current card sd.power(0) sd.power(1) dis.fullscreen('Part Erase...') cutoff = 1024 # arbitrary blk = bytearray(512) for bnum in range(cutoff): callgate.fill_random(blk) sd.writeblocks(bnum, blk) dis.progress_bar_show(bnum / cutoff) dis.fullscreen('Formating...') # remount, with newfs option os.mount(sd, '/sd', readonly=0, mkfs=1) # done, cleanup os.umount('/sd') # important: turn off power sd = pyb.SDCard() sd.power(0)
def toggle_led_sd(x, butpress=sd_detect, light=led, sd_spi=spi, sd_cs=cs, getinfo=pd_txtfiles): global irq_busy_sd, sd_out, sd if irq_busy_sd: return else: irq_busy_sd = True if butpress.value() == 1: # reverse op == 0 if sd_out is True: print('SD card detected') for i in range(4): led.value(not led.value()) time.sleep_ms(250) butpress.init(Pin.OUT) sd = sdcard.SDCard(sd_spi, sd_cs) time.sleep_ms(1000) os.mount(sd, '/sd') print(os.listdir('/')) # butpress.value(0) # reverse op == 1 butpress.init(Pin.IN) getinfo("/sd") sd_out = False # butpress.init(Pin.IN, Pin.PULL_UP) elif butpress.value() == 0: if sd_out is False: print('SD card removed') for i in range(4): led.value(not led.value()) time.sleep_ms(250) time.sleep_ms(1000) butpress.init(Pin.OUT) os.umount('/sd') time.sleep_ms(1000) sd_out = True irq_busy_sd = False
def prepare_for_shutdown(self): if self.sd_mounted: _logger.info("Unmounting SD card") try: os.umount(self.SDCARD_MOUNT_POINT) except: _logger.exception("Could not unmount SD card") try: self.power_peripherals(False) except: _logger.exception("Could not cut power to peripherals") try: self.hold_pins() except: _logger.exception("Could not hold pins") try: self.set_wake_on_flash_pin() except: _logger.exception("Could not set wake on flash pin")
def load(debug=False, sd=None): """ Load off SD our AP, pw, and URL details :param debug: Logging :param sd: SD object if mounted already :return: Config object """ from machine import SD cfg = None try: unmount = False if sd is None: sd = SD() os.mount(sd, '/sd') unmount = True cfg = Config.load_file(open(Config.SD_CONFIG_PATH,"r"), debug) if unmount: try: os.unmount('/sd') # got renamed in upy 1.9 except AttributeError: os.umount('/sd') sd.deinit() del sd except OSError: print("Can't open config file SD card") if not cfg: cfg = Config.load_file(open(Config.FLASH_CONFIG_PATH, "r"), debug) if not cfg: raise ValueError("No config file!") print("Loaded from flash") cfg.src = "flash" else: print("Loaded from SD card") cfg.src = "sd" return cfg
def umount(): global SD,spi try: os.umount("/sd") try: SD.deinit() del SD except: pass try: spi.deinit() del spi except: pass # let all SD pins be inputs import sdpin for i in sdpin.hiz: p = Pin(i,Pin.IN) a = p.value() del p, a return True except: return False
def change_file(self): oldselected = self.fb_selected - self.fb_topitem self.fb_selected = self.fb_cursor try: filename = self.fullpath(self.direntries[self.fb_cursor][0]) except: filename = False self.fb_selected = -1 self.show_dir_line(oldselected) self.show_dir_line(self.fb_cursor - self.fb_topitem) if filename: if filename.endswith(".bit"): self.spi_request.irq(handler=None) self.timer.deinit() self.enable[0] = 0 self.osd_enable(0) self.spi.deinit() tap = ecp5.ecp5() tap.prog_stream(open(filename, "rb"), blocksize=1024) if filename.endswith("_sd.bit"): os.umount("/sd") for i in bytearray([2, 4, 12, 13, 14, 15]): p = Pin(i, Pin.IN) a = p.value() del p, a result = tap.prog_close() del tap gc.collect() #os.mount(SDCard(slot=3),"/sd") # BUG, won't work self.init_spi() # because of ecp5.prog() spi.deinit() self.spi_request.irq(trigger=Pin.IRQ_FALLING, handler=self.irq_handler_ref) self.irq_handler(0) # handle stuck IRQ if filename.endswith(".nes") \ or filename.endswith(".snes") \ or filename.endswith(".smc") \ or filename.endswith(".sfc"): import ld_nes s = ld_nes.ld_nes(self.spi, self.cs) s.ctrl(1) s.ctrl(0) s.load_stream(open(filename, "rb"), addr=0, maxlen=0x101000) del s gc.collect() self.enable[0] = 0 self.osd_enable(0) if filename.startswith( "/sd/ti99_4a/") and filename.lower().endswith(".bin"): import ld_ti99_4a s = ld_ti99_4a.ld_ti99_4a(self.spi, self.cs) s.load_rom_auto(open(filename, "rb"), filename) del s gc.collect() self.enable[0] = 0 self.osd_enable(0) if (filename.startswith("/sd/msx") and filename.endswith(".rom")) \ or filename.endswith(".mx1"): import ld_msx s = ld_msx.ld_msx(self.spi, self.cs) s.load_msx_rom(open(filename, "rb")) del s gc.collect() self.enable[0] = 0 self.osd_enable(0) if filename.endswith(".z80"): self.enable[0] = 0 self.osd_enable(0) import ld_zxspectrum s = ld_zxspectrum.ld_zxspectrum(self.spi, self.cs) s.loadz80(filename) del s gc.collect() if filename.endswith(".ora") or filename.endswith(".orao"): self.enable[0] = 0 self.osd_enable(0) import ld_orao s = ld_orao.ld_orao(self.spi, self.cs) s.loadorao(filename) del s gc.collect() if filename.endswith(".vsf"): self.enable[0] = 0 self.osd_enable(0) import ld_vic20 s = ld_vic20.ld_vic20(self.spi, self.cs) s.loadvsf(filename) del s gc.collect() if filename.endswith(".prg"): self.enable[0] = 0 self.osd_enable(0) import ld_vic20 s = ld_vic20.ld_vic20(self.spi, self.cs) s.loadprg(filename) del s gc.collect() if filename.endswith(".cas"): self.enable[0] = 0 self.osd_enable(0) import ld_trs80 s = ld_trs80.ld_trs80(self.spi, self.cs) s.loadcas(filename) del s gc.collect() if filename.endswith(".cmd"): self.enable[0] = 0 self.osd_enable(0) import ld_trs80 s = ld_trs80.ld_trs80(self.spi, self.cs) s.loadcmd(filename) del s gc.collect()
def close(self): if self.vfs is not None: umount('/fc') print("SD Desmontada")
# inicializacion modulo SD Pin(18, Pin.OUT, value=1) #para desactivar LoRa spi = SPI(sck=Pin(23), miso=Pin(12), mosi=Pin(13)) sd = sdcard.SDCard(spi, Pin(2, Pin.OUT)) oled.text('Modulo SD listo', 0, 10) oled.show() # inicializacion modulo GPS gps = UART(2, 115200) gps.init(9600, bits=8, parity=None, stop=1, tx=17, rx=5) oled.text('Gps...OK', 0, 20) oled.show() os.mount(sd, '/fc') gps_data = 'hola123' filename = '/fc/gps_data.txt' with open(filename, 'w') as f: n = f.write(gps_data) print(n, 'bytes written') with open(filename, 'r') as f: result1 = f.read() print(len(result1), 'bytes read') os.umount('/fc') time.sleep(0.8) Pin(25, Pin.OUT, value=0) time.sleep(0.8) Pin(25, Pin.OUT, value=1)
grub_partition = "(hd%c,%c)" % ( partition[ "name" ][ -2 ], partition[ "name" ][ -1 ] ) f = open( "/media/install/boot/grub/menu.lst", "w" ) f.write( "title yaOSp\n" ) f.write( "root %s\n" % grub_partition ) f.write( "kernel /system/kernel root=%s\n" % ( partition[ "name" ] ) ) f.write( "module /system/module/bus/pci\n" ) f.write( "module /system/module/disk/pata\n" ) f.write( "module /system/module/disk/partition\n" ) f.write( "module /system/module/filesystem/ext2\n" ) f.write( "module /system/module/input/ps2\n" ) f.write( "module /system/module/input/input\n" ) f.write( "module /system/module/char/terminal\n" ) f.close() os.umount( "/media/install" ) # We're done :) print print "The installation of yaOSp is done." print "You have to restart and install GRUB manually by following these steps:" print " * Press 'c' when GRUB is loaded" print " * Type 'root %s'" % ( grub_partition ) print " * Type 'setup (hd%c)'" % ( partition[ "name" ][ -2 ] ) print " * You're done, remove the CD and reboot." print print "Thanks for choosing yaOSp :)"
def umount_sd(): os.umount('/sd') ls('/')
# SD card import machine, os # Slot 2 uses pins sck=18, cs=5, miso=19, mosi=23 sd = machine.SDCard(slot=2) os.mount(sd, "/sd") # mount os.listdir('/sd') # list directory contents os.umount('/sd') # eject
def umount(self, root): os.umount(root)
def sdtest(): print("1") #hardware spi spi = SPI(2, baudrate=10000000, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=Pin(18, Pin.OUT, Pin.PULL_DOWN), mosi=Pin(23, Pin.OUT, Pin.PULL_UP), miso=Pin(19, Pin.IN, Pin.PULL_UP)) spi.init() # Ensure right baudrate sd = sdcard.SDCard(spi, Pin(22)) # Compatible with PCB vfs = os.VfsFat(sd) os.mount(vfs, "/fc") print("Filesystem check") print(os.listdir("/fc")) print("1") line = "abcdefghijklmnopqrstuvwxyz\n" lines = line * 200 # 5400 chars short = "1234567890\n" print("1") fn = "/fc/rats.txt" print() print("Multiple block read/write") with open(fn, "w") as f: n = f.write(lines) print(n, "bytes written") n = f.write(short) print(n, "bytes written") n = f.write(lines) print(n, "bytes written") with open(fn, "r") as f: result1 = f.read() print(len(result1), "bytes read") fn = "/fc/rats1.txt" print() print("Single block read/write") with open(fn, "w") as f: n = f.write(short) # one block print(n, "bytes written") with open(fn, "r") as f: result2 = f.read() print(len(result2), "bytes read") os.umount("/fc") print() print("Verifying data read back") success = True if result1 == "".join((lines, short, lines)): print("Large file Pass") else: print("Large file Fail") success = False if result2 == short: print("Small file Pass") else: print("Small file Fail") success = False print() print("Tests", "passed" if success else "failed")
self.readinto(mv[offset : offset + 512]) offset += 512 nblocks -= 1 return self.cmd_nodata(b'\x0c') return 0 def writeblocks(self, block_num, buf): nblocks, err = divmod(len(buf), 512) assert nblocks and not err, 'Buffer length is invalid' if nblocks == 1: if self.cmd(24, block_num * self.cdv, 0) != 0: return 1 self.write(_TOKEN_DATA, buf) else: if self.cmd(25, block_num * self.cdv, 0) != 0: return 1 offset = 0 mv = memoryview(buf) while nblocks: self.write(_TOKEN_CMD25, mv[offset : offset + 512]) offset += 512 nblocks -= 1 self.write_token(_TOKEN_STOP_TRAN) return 0 import machine, sdcard, os sd = sdcard.SDCard(machine.SPI(0), machine.Pin(15)) os.umount() os.VfsFat(sd, "") os.listdir()
time.sleep_ms(200) try: measurement = scd30.read_measurement() data['co2'] = measurement[0][0] data['temperature'] = measurement[1][0] data['humidity'] = measurement[2][0] print('co2: {}, temperature: {}, humidity: {}'.format( data['co2'], data['temperature'], data['humidity'])) except SCD30.CRCException: print('CRC exception during measurement reading SCD30') errled.on() pass # Create logfile per day... datetimeformat = '{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}' isodatetime = datetimeformat.format(t[0], t[1], t[2], t[3], t[4], t[5]) name = 'sensordata_{:04d}_{:02d}_{:02d}.log'.format(t[0], t[1], t[2]) with open("/sd/" + name, "a") as f: f.write("{};{};{};{};\n".format(isodatetime, data['co2'], data['temperature'], data['humidity'])) os.umount('/sd') sd.power(0) en_3v3.value(0) led.off() # Sleep for 300 seconds... time.sleep(300)