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 mount(self): try: self.sd = SDCard(slot=3) uos.mount(self.sd,"/sd") return True except: return False
async def play_wav(): bck_pin = Pin(21) ws_pin = Pin(22) sdout_pin = Pin(27) # channelformat settings: # mono WAV: channelformat=I2S.ONLY_LEFT audio_out = I2S( I2S.NUM0, bck=bck_pin, ws=ws_pin, sdout=sdout_pin, standard=I2S.PHILIPS, mode=I2S.MASTER_TX, dataformat=I2S.B16, channelformat=I2S.ONLY_LEFT, samplerate=SAMPLE_RATE_IN_HZ, dmacount=10, dmalen=512) # configure SD card # slot=2 configures SD card to use the SPI3 controller (VSPI), DMA channel = 2 # slot=3 configures SD card to use the SPI2 controller (HSPI), DMA channel = 1 sd = SDCard(slot=3, sck=Pin(18), mosi=Pin(23), miso=Pin(19), cs=Pin(4)) uos.mount(sd, "/sd") wav_file = '/sd/{}'.format(WAV_FILE) wav = open(wav_file,'rb') # advance to first byte of Data section in WAV file pos = wav.seek(44) # allocate sample arrays # memoryview used to reduce heap allocation in while loop wav_samples = bytearray(1024) wav_samples_mv = memoryview(wav_samples) print('Starting ... ') # continuously read audio samples from the WAV file # and write them to an I2S DAC try: while True: num_read = wav.readinto(wav_samples_mv) num_written = 0 # end of WAV file? if num_read == 0: # advance to first byte of Data section pos = wav.seek(44) else: # loop until all samples are written to the I2S peripheral while num_written < num_read: num_written += audio_out.write(wav_samples_mv[num_written:num_read], timeout=0) await asyncio.sleep_ms(10) except (KeyboardInterrupt, Exception) as e: print('caught exception {} {}'.format(type(e).__name__, e)) raise finally: wav.close() uos.umount("/sd") sd.deinit() audio_out.deinit() print('Done')
def mount(): global SD,spi try: # ESP32 from machine import SDCard SD=SDCard(slot=3) os.mount(SD,"/sd") except: try: # ESP32-S2 import sdpin from sdcard import SDCard from machine import SPI spi=SPI(sck=Pin(sdpin.clk), mosi=Pin(sdpin.cmd), miso=Pin(sdpin.d0)) SD=SDCard(spi,Pin(sdpin.d3)) os.mount(SD,"/sd") except: print("mount failed") return False return True
def __init__(self): try: os.mount( SDCard(slot=3, miso=Pin(12), mosi=Pin(13), sck=Pin(14), cs=Pin(15)), "/sd") except: print("Sd card could not be read")
def start(self): try: self.sdcard = SDCard(slot=2, miso=Pin(self.miso), mosi=Pin(self.mosi), sck=Pin(self.sck), cs=Pin(self.cs)) self.inited = True self.mount() except Exception as e: sys.print_exception(e) print('sd init failure')
def _init_card(self): try: if self._card is None: self._card = SDCard(slot=SLOT, mosi=PIN_MOSI, miso=PIN_MISO, sck=PIN_SCK, cs=PIN_CS) except Exception: raise Exception("Card reader not present") return self._card
def init(): global __sdcard if __sdcard == None: try: sd = SDCard( slot=3, width=1, sck=Pin(PIN_SD_SCK), miso=Pin(PIN_SD_MISO), mosi=Pin(PIN_SD_MOSI), cs=Pin(PIN_SD_CS), # freq=20_000_000 ) __sdcard = __SDCardBlockDevice(sd) except: pass
def mount_sdcard(slot_num, mount_point): global SDCARD_MOUNTED sdcard = SDCard(slot=slot_num) tries_remaining = 10 while tries_remaining: try: mount(sdcard, mount_point) except OSError as e: print('Could not mount SD Card: OSError {}'.format(e)) else: print('Mounted SD Card at: {}'.format(mount_point)) SDCARD_MOUNTED = True break tries_remaining -= 1 if tries_remaining == 0: break print('Trying again to mount SD Card...') sleep(1)
def __init__(self, slot=2, pin=4) -> None: self.sd = SDCard(slot=slot, cs=Pin(pin))
from machine import Pin, I2C, SDCard, freq from os import mount import time, ntptime, mcp7940, ecp5 freq(240 * 1000 * 1000) sd = SDCard(slot=3) # 1-bit mode mount(sd, "/sd") ecp5.prog("/sd/rtc/ulx3s_12f_i2c_bridge.bit") i2c = I2C(sda=Pin(16), scl=Pin(17), freq=400000) mcp = mcp7940.MCP7940(i2c) mcp.control = 0 mcp.trim = -29 #mcp.battery=1 #print("battery %s" % ("enabled" if mcp.battery else "disabled")) print("trim %+d ppm" % mcp.trim) print("control 0x%02X" % mcp.control) print("setting time.localtime() to NTP time using ntptime.settime()") ntptime.settime() print("after NTP, time.localtime() reads:") print(time.localtime()) print("setting mcp.time=time.localtime()") mcp.stop() mcp.time = time.localtime() print("after setting:") print("battery %s" % ("enabled" if mcp.battery else "disabled")) print("mcp.time reads:") # Read time after setting it, repeat to see time incrementing for i in range(3): print(mcp.time)
audio_out = I2S(I2S.NUM0, bck=bck_pin, ws=ws_pin, sdout=sdout_pin, standard=I2S.PHILIPS, mode=I2S.MASTER_TX, dataformat=I2S.B16, channelformat=I2S.ONLY_LEFT, samplerate=SAMPLE_RATE_IN_HZ, dmacount=10, dmalen=512) # configure SD card # slot=2 configures SD card to use the SPI3 controller (VSPI), DMA channel = 2 # slot=3 configures SD card to use the SPI2 controller (HSPI), DMA channel = 1 sd = SDCard(slot=3, sck=Pin(18), mosi=Pin(23), miso=Pin(19), cs=Pin(22)) uos.mount(sd, "/sd") wav_file = '/sd/{}'.format(WAV_FILE) wav = open(wav_file, 'rb') # advance to first byte of Data section in WAV file pos = wav.seek(44) # allocate sample arrays # memoryview used to reduce heap allocation in while loop wav_samples = bytearray(1024) wav_samples_mv = memoryview(wav_samples) print('Starting') # continuously read audio samples from the WAV file # and write them to an I2S DAC
# Drum loop from Zapsplat.com: # https://www.zapsplat.com/sound-effect-category/loops/ # Setup: # copy wavplayer.py to your filesystem # copy .wav files to a SD card import os import time from machine import Pin from wavplayer import WavPlayer # configure and mount SD card from machine import SDCard sd = SDCard(slot=2) # sck=18, mosi=23, miso=19, cs=5 os.mount(sd, "/sd") # list files to your SD card os.listdir('/sd') # ['fart.wav', 'drum_loop_1.wav', 'drum_loop_3.wav', 'drum_loop_3.wav'] # adjust the gain (volume) # gain = Pin(14) # gain.init(Pin.IN, pull=Pin.PULL_DOWN) # gain 5: louder # gain.init(Pin.OUT, value=0) # gain 4: loud # gain.init(Pin.IN, pull=None) # gain 3: middle # gain.init(Pin.OUT, value=1) # gain 2: quiet # gain.init(Pin.IN, pull=Pin.PULL_UP) # gain 1: quieter # init WavPlayer
import uos import time import camera from machine import SDCard uos.mount(SDCard(), '/sd') uos.chdir('sd') camera.init(0, format=camera.JPEG) i = 0 while i < 10000: buf = camera.capture() imgname = str(i) + ".jpg" img = open(imgname, 'w') img.write(buf) img.close() time.sleep(1) i += 1
from machine import SDCard import uos uos.mount(SDCard(slot=2, mosi=15, miso=2, sck=14, cs=13), "/sd")
import sys import mimxrt from machine import Pin bdev = mimxrt.Flash() try: vfs = os.VfsLfs2(bdev, progsize=256) except: os.VfsLfs2.mkfs(bdev, progsize=256) vfs = os.VfsLfs2(bdev, progsize=256) os.mount(vfs, "/flash") os.chdir("/flash") sys.path.append("/flash") sys.path.append("/flash/lib") # do not mount the SD card if SKIPSD exists. try: os.stat("SKIPSD") except: try: from machine import SDCard sdcard = SDCard(1) fat = os.VfsFat(sdcard) os.mount(fat, "/sdcard") os.chdir("/sdcard") sys.path.append("/sdcard") except: pass # Fail silently
print("SD card did not mount correctly") # TODO: add LED sigal from board to signify this try: umount("/sdcard") except OSError as e: # TODO: add LED signal from board to signify this print("Reinsert SD Card in SD Card reader") # TODO: remove sleep once LED signal is done # sleep gives time to read comment before reseting the board sleep(3) reset() # mount SD card sd_gdt = GDT(2, station, func=sd_gdt_func) mount(SDCard(slot=3), "/sdcard") sd_gdt.deinit_timer() del sd_gdt collect() config_file = "/sdcard/pmt.conf" default = "/sdcard/pmt.log" wifi = "/sdcard/wifi.log" archive = "/sdcard/data.log" unsent = "/sdcard/buffer.log" blacklist = "/sdcard/blacklist.log" current_ap = "/sdcard/SSID.log" unsent_buffer_ptr = "/sdcard/buffer_pointer.log" # create file for initial read with open(blacklist, "a+"):
def sd_open(self): self.sd = SDCard(slot=3)
self.spi_freq = const(100000) self.init_spi() s = ld_ti99_4a.ld_ti99_4a(self.spi, self.cs) print("Saving memory from {} length {} file: {}".format( addr, length, filename)) s.save_stream(open(filename, "wb"), addr, length) del s self.spi_freq = old_freq self.init_spi() gc.collect() # FPGA init function not part of class. def load_fpga(): fpga_config_file = "/sd/ti99_4a/bitstreams/ti994a_ulx3s.bit" print("FPGA file: {}".format(fpga_config_file)) ecp5.prog(fpga_config_file) # ulx3s_85f_spi_ti99_4a.bit") gc.collect() def reset(): import machine machine.reset() os.mount(SDCard(slot=3), "/sd") load_fpga() run = osd() run.load_roms()
'bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files', 'ffree', ] info = dict(zip(statvfs_fields, os.statvfs('/flash'))) print(info) print(info['bsize'] * info['bfree']) import uos from machine import SDCard sd = SDCard(slot=2, mosi=23, miso=19, sck=18, cs=4) uos.mount(sd, "/sd") print(uos.listdir('/sd/')) import network wlan = network.WLAN(network.STA_IF) # create station interface print(wlan.active(True)) # activate the interface print(wlan.scan()) # scan for access points print(wlan.isconnected()) # check if the station is connected to an AP print(wlan.connect('ChinaDaddy', 'Mdzz7788')) # connect to an AP print(wlan.config('mac')) # get the interface's MAC address print(wlan.ifconfig()) # get the interface's IP/netmask/gw/DNS addresses # from machine import RTC
# This file is executed on every boot (including wake-boot from deepsleep) from gc import collect from esp import osdebug from time import sleep from ujson import load import webrepl from uos import mount, umount from machine import unique_id, SDCard osdebug(None) collect() try: mount(SDCard(slot=2, width=1, sck=14, miso=15, mosi=13, cs=5), "/fc") SD=True print("SD mounted") except Exception as e: SD=False print("SD not mounted") def readwificfg(): try: file_name = "/fc/wifi.json" with open(file_name) as json_data_file: data = load(json_data_file) return data except Exception as e: print(repr(e)) return None def get_id(): x = [hex(int(c)).replace("0x","") for c in unique_id()]
ads_address = i break del found # adc import ads1015 ads = ads1015.ADS1015(i2c, ads_address, gain=1) # mcp23017 import mcp23017 mcp = mcp23017.MCP23017(i2c, mcp_address) # sd card import uos as os from machine import SDCard sd = SDCard(slot=2) sd_cd = Pin(33, Pin.IN) # if sd card detect pin is LOW, a card is inserted if sd_cd.value() == 0: try: print('Found SD card {}'.format(sd.info())) os.mount(sd, '/sd') print('Mounted SD card at /sd') except OSError: print('Failed to mount SD card') else: print('SD card not inserted') # deinit sd with # os.umount('/sd')
# octopusLAB - TFT128x160 and ESP32board - 2020/06 from machine import Pin, SPI, SDCard from time import sleep, sleep_ms # from utils.octopus import * from utils.pinout import set_pinout pinout = set_pinout() print("mount SD card >") uos.mount(SDCard(slot=2, freq=16000000), "/sd") import framebuf from lib import st7735 from lib.rgb import color565 print("spi.TFT 128x160 init >") spi = SPI(1, baudrate=10000000, polarity=1, phase=0, sck=Pin(pinout.SPI_CLK_PIN), mosi=Pin(pinout.SPI_MOSI_PIN)) ss = Pin(pinout.SPI_CS0_PIN, Pin.OUT) cs = Pin(25, Pin.OUT) #SCE0() > PWM3(25) dc = Pin(33, Pin.OUT) #PWM2(16) > DEV2(33) rst = Pin(27, Pin.OUT) #PWM1(17) > DEv3(27) tft = st7735.ST7735R(spi, cs = cs, dc = dc, rst = rst) print("spi.TFT framebufer >") # Initialize FrameBuffer of TFT's size fb = framebuf.FrameBuffer(bytearray(tft.width*tft.height*2), tft.width, tft.height, framebuf.RGB565) fbp = fb.pixel fb.fill(color565(255,0,0))
if TTGO: pass else: #windows curdir = os.curdir print(curdir) # '.' # ziel bereitstellen ( in ttgo sd card via spi verbinden) # bei ttgo sd mount sd card if TTGO: from machine import SDCard filesystem = SDCard(slot=2, width=1, cd=None, wp=None, sck=14, miso=2, mosi=15, cs=13) os.mount( filesystem, '/sd') #Will raise OSError(EPERM) if mount_point is already mounted. print("Filesystem check") print(os.listdir('/sd')) else: # windows # make zieldirectory, falls noch nicht vorhanden if os.path.isdir('./subdir'): pass else: os.mkdir("subdir")
ws=ws_pin, sdout=sdout_pin, standard=I2S.PHILIPS, mode=I2S.MASTER_TX, dataformat=I2S.B16, channelformat=I2S.ONLY_LEFT, samplerate=SAMPLE_RATE_IN_HZ, dmacount=10, dmalen=512) # configure SD card: # See [docs](https://docs.micropython.org/en/latest/library/machine.SDCard.html#esp32) for # recommended pins depending on the chosen slot. # slot=2 configures SD card to use the SPI3 controller (VSPI), DMA channel = 2 # slot=3 configures SD card to use the SPI2 controller (HSPI), DMA channel = 1 sd = SDCard(slot=2, sck=Pin(18), mosi=Pin(23), miso=Pin(19), cs=Pin(5)) uos.mount(sd, "/sd") wav_file = '/sd/{}'.format(WAV_FILE) wav = open(wav_file, 'rb') # advance to first byte of Data section in WAV file pos = wav.seek(44) # allocate sample arrays # memoryview used to reduce heap allocation in while loop wav_samples = bytearray(1024) wav_samples_mv = memoryview(wav_samples) print('Starting') # continuously read audio samples from the WAV file # and write them to an I2S DAC
def mount(): """ Setup sd card object and mount to file system. """ sd = SDCard(slot=COMM_SLOT, sck=P_SCK, miso=P_MISO, mosi=P_MOSI, cs=P_CS) os.mount(sd, ROOT) return sd
(addr >> 8) & 0xFF, addr & 0xFF ])) self.spi.write(data) self.cs.off() self.ctrl(4) self.ctrl(0) def peek(addr, length=1): return run.peek(addr, length) def poke(addr, data): run.poke(addr, data) #bitstream="/sd/mac/bitstreams/ulx3s_v20_85f_mac128.bit" bitstream = "/xyz.bit" try: freq(240 * 1000 * 1000) # 80/160/240 MHz, faster CPU = faster SD card #os.mount(SDCard(slot=3),"/sd") # 1-bit SD mode os.mount( SDCard(), "/sd" ) # 4-bit SD mode (mac bitstream must be flashed or already loaded) import ecp5 ecp5.prog(bitstream) except: print(bitstream + " file not found") gc.collect() run = osd()
def __init__(self, slot=2, pin=4, mount_folder="/sd") -> None: self.__sd = SDCard(slot=slot, cs=Pin(pin))
def __init__(self, pi_set_pin=5, pi_unset_pin=33, pi_powered_pin=25, pi_powered_inv=False, pi_heartbeat_pin=26, pi_shutdown_pin=27, pi_shutdown_inv=True, votronic_port=2, votronic_de_pin=4, votronic_de_inv=False, votronic_re_pin=2, votronic_re_inv=True): # Mount the SD card and open a log file for debugging. self.logfile = None try: os.mount(SDCard(slot=3, sck=14, miso=12, mosi=13, cs=15), '/sd') self.logfile = open('/sd/phlox.log', 'a') except Exception as e: print_exception(e) self.log('Phlox initializing...') # We're using the Perthensis scheduler for multitasking. self.sch = sch = Scheduler() # Raspberry Pi controller object. # It will automatically switch the Pi on when initializing. self.pi = Pi( Signal(pi_powered_pin, Pin.IN, invert=pi_powered_inv), # Signal class inverts the constructor value if invert is True. Signal(pi_shutdown_pin, Pin.OUT, invert=pi_shutdown_inv, value=0), Signal(pi_heartbeat_pin, Pin.IN, Pin.PULL_DOWN), LatchingRelay(pi_set_pin, pi_unset_pin), sch, self.log, ) # Default sleep state is "enable everything". self.set_sleepstate(0) # Initialize Votronic RS485 interface via Arduino MKR 485 shield. self.votronic = microtonic.UART( votronic_port, Signal(votronic_re_pin, Pin.OUT, invert=votronic_re_inv), Signal(votronic_de_pin, Pin.OUT, invert=votronic_de_inv), ) self.votronic.on_packet = self.votronic_packet sch(self.votronic.read) # Prepare WLAN and MQTT. self.wlan = self.mqtt = None try: with open('wlan.json') as f: self.wlan = WLANClient(**json.load(f)) except Exception as e: print_exception(e) if self.wlan is not None: # Add WLAN client to scheduler. sch(self.wlan.watch) # Set up MQTT. self.mqtt = MQTTClient('10.115.106.254', client_id='phlox', keepalive=30) self.mqtt.set_last_will('jessie/phlox/up', '0', True) self.mqtt.on_connect = self.mqtt_connected self.mqtt.set_callback(self.mqtt_msg) self.mqtt.subscribe('jessie/sleepstate') sch(self.mqtt.watch) self.log('Initialized.')
# init sensors and fan tempsensor = Tempsensor(pin=settings.PINS['tempsensor']) tempsensor_aux = Tempsensor(pin=settings.PINS['tempsensor_aux']) fan = PWMFan(pin=settings.PINS['fan'], led_pin=settings.PINS['fan_led']) fan_controller = PIDFanTempController(fan, tempsensor, buzzer, settings.TARGET_TEMPERATURE) # init buttons # full throttle Toggle(pin=settings.PINS['full_throttle_toggle'], action=fan.full_throttle, cancel_action=fan.auto) # test Toggle(pin=settings.PINS['test_toggle'], action=buzzer.test_on, cancel_action=buzzer.test_off) try: # mount sd card uos.mount(SDCard(slot=2, sck=18, miso=19, mosi=23, cs=5), settings.SD_CARD_PATH) except Exception as e: buzzer.play_error2_signal() logger.exc(e, 'FLASH CARD ERROR') else: # init data logger data_logger = CSVDataLogger(['time', 'temp', 'temp_aux', 'speed', 'adc', 'adc_value', 'adc_aux', 'adc_value_aux']) # init timer main_timer = Timer(-1) operational_counter = 0 logger.info('Initialization complete') buzzer.play_turn_on_signal() except Exception as e: log_and_restart(e)