def __init__(self): self._name = "Westhill Laser Measument System" self._wlan = network.WLAN(network.STA_IF) self.connect_wifi() self._sd = machine.SDCard(slot=3, sck=machine.Pin(14), miso=machine.Pin(12) ,mosi=machine.Pin(13),cs=machine.Pin(15)) uos.mount(self._sd, SD_FILE) self._th_sensor = si7021.SI7021(4, 21) self._buzz = Buzzer(26)
def mountsd(mountpoint="/sd"): """ Mount command """ import uos import machine try: uos.mount(machine.SDCard(), mountpoint) print("Sd mounted on '%s'" % mountpoint) except: print("Cannot mount sd on '%s'" % mountpoint)
def mount(self): sd = machine.SDCard(slot=3, sck=18, mosi=23, miso=38, cs=4) try: uos.mount(sd, "/sd") except Exception as exc: print("Exception:", exc.args[0]) print("/sd:", uos.listdir("/sd"))
def open(self): """ Open and mount sd card """ if self.opened == False: try: uos.mount(machine.SDCard(), self.mountpoint) print("Mount %s" % self.mountpoint) self.opened = True except Exception as error: # print(exception(error)) print("Cannot mount %s" % self.mountpoint) return self.opened
def main(): # setup sensors bus = machine.I2C(scl=machine.Pin(16), sda=machine.Pin(13)) bme = BME280(i2c=bus) # setup storage card = machine.SDCard() os.mount(card, '/card') # setup networking config = load_config('/card', 'config.yml') eth = start_network(config) # setup Prometheus metrics registry = CollectorRegistry(namespace='prometheus_express') metric_c = Counter('system_heartbeat', 'system heartbeat counter', labels=['location'], registry=registry) metric_g = Gauge('sensor_temperature', 'temperature data from the sensors', labels=['location', 'sensor'], registry=registry) router = Router() router.register('GET', '/metrics', registry.handler) server = False # wait for incoming connection while True: while not server: time.sleep(1) server = bind(eth, config) location = config['metric_location'] metric_c.labels(location).inc(1) metric_g.labels(location, 'esp32').set(temp_ftoc(esp32.raw_temperature())) metric_g.labels(location, 'bme280').set(bme.read_compensated_data()[0]) try: server.accept(router) except OSError as err: print('Error accepting request: {}'.format(err)) except ValueError as err: print('Error parsing request: {}'.format(err))
def __init__(self, *args, **kwds): super().__init__(*args, **kwds) self.tabview = lv.tabview(self) self.tabview.set_size(240, 320) self.tabview.align(self, lv.ALIGN.IN_TOP_MID, 0, 0) self.mainpage = main.Page_Main(self.tabview.add_tab("Main")) self.wifipage = wifi.Page_WiFi(self.tabview.add_tab("WiFi"), self) self.appspage = apps.Page_Apps(self.tabview.add_tab("Apps"), self) try: self.sd = machine.SDCard(slot=2, sck=14, miso=12, mosi=13, cs=15) uos.mount(self.sd, '/sd') print("SD card mounted") self.mainpage.set_status("sdcard", True) except Exception as e: import sys sys.print_exception(e)
def boot_main(): # load config card = machine.SDCard() os.mount(card, '/card') sys.path.append('/card/lib') from redesigned_barnacle.config import load_config from redesigned_barnacle.ota import chain_load config = load_config('/card', 'config.yml') print('Card config: ', config) # chain the card loader chain_module = chain_load(config['image_name'], [ '/card/lib', '/card/app', ]) return chain_module.chain_main(config)
def setup_sd(logger): microsd_config = { "miso": 2, "mosi": 15, "ss": 13, "sck": 14, } logger.debug("microsd_config: {}".format(microsd_config)) sd = machine.SDCard( slot=3, width=1, sck=machine.Pin(microsd_config["sck"]), mosi=machine.Pin(microsd_config["mosi"]), miso=machine.Pin(microsd_config["miso"]), cs=machine.Pin(microsd_config["ss"]), ) logger.debug("sd card initialized: {}".format(sd)) return sd
# This file is executed on every boot (including wake-boot from deepsleep) #import esp #esp.osdebug(None) import webrepl webrepl.start() import wifiConnect #wifiConnect.connect('TIM-37482183', 'HnbD76SPtLs7G8vS') #if network not found start Access Point mode wifiConnect.connect('RedmiMau', 'mau12397') #if network not found start Access Point mode import machine import os try: uos.mount(machine.SDCard(), "/sd") os.chdir("sd") except: print("could not mount SD card")
import gc import uos import machine from flashbdev import bdev try: #if bdev: # uos.mount(bdev, "/") sd = machine.SDCard(slot=2, width=1, cd=None, wp=None, sck=None, miso=None, mosi=None, cs=5, freq=20000000) uos.mount(sd, "/") except OSError: import inisetup vfs = inisetup.setup() gc.collect()
# Examples using the MicroSD Card import machine import uos as os # no sd card mounted os.listdir() ['boot.py', 'main.py'] sd = machine.SDCard(slot=2) # I (1090900) gpio: GPIO[5]| InputEn: 0| OutputEn: 1| OpenDrain: 0| Pullup: 0| Pulldown: 0| Intr:0 sd.info() #(7948206080, 512) # mount os.mount(sd, '/sd') os.listdir() #['sd', 'boot.py', 'main.py'] os.listdir('/sd') # ['hello.py'] # write f = open('/sd/test.py', 'w') f.write('print(\'hello\')\n') f.close() # read f = open('/sd/test.py', 'r')
def sd_init(): global sd sd = machine.SDCard(slot=1, width=1, freq=40000000) uos.mount(sd, '/sd') print(uos.listdir('/sd'))
import time time.sleep(1) import machine as m import os try: os.mount(m.SDCard(slot=1, mosi=15, miso=2, sck=14, cs=13), "/sd") except: os.mount(m.SDCard(slot=2, mosi=15, miso=2, sck=14, cs=13), "/sd") print(os.listdir("/sd")) os.chdir("/sd") from main_sd import *
def MountSD(aDir: str = '/sd'): SD = machine.SDCard() os.mount(SD, aDir)
from time import sleep_ms import os, machine, gc from ssd1306 import SSD1306_I2C from machine import I2C, Pin import framebuf, time SD_SW = Pin(5, Pin.IN) os.mount(machine.SDCard(), '/sd') i2c = I2C(sda=Pin(23), scl=Pin(22)) display = SSD1306_I2C(128, 64, i2c) for i in range(1, 41): dirt = 'sd/BAD_APPLE/' + str(i) + '.pbm' print(i) with open(dirt, 'rb') as f: f.readline() f.readline() data = bytearray(f.read()) fbuf = framebuf.FrameBuffer(data, 88, 64, framebuf.MONO_HLSB) display.fill(0) display.blit(fbuf, 19, 0) display.show() del fbuf time.sleep(0.2)
def main(): # setup sensors bus = CircuitI2C(scl=machine.Pin(16), sda=machine.Pin(13)) bme = BME280(i2c=bus) oled = SSD1306_I2C(128, 32, bus) ss = Seesaw(bus, addr=0x36) # setup storage card = machine.SDCard() os.mount(card, '/card') # setup networking config = load_config('/card', 'config.yml') eth = eth_start(config, mdc=machine.Pin(23), mdio=machine.Pin(18), phy_type=network.PHY_LAN8720, phy_addr=0, clock_mode=network.ETH_CLOCK_GPIO17_OUT, power_pin=machine.Pin(12, machine.Pin.OUT)) # setup display sb = CircularBuffer(16, 8) sl = Sparkline(16, 128, sb) oled.init_display() oled.fill(0x0) oled.text('00.00', 0, 0) oled.show() # setup Prometheus metrics #region: metrics registry = CollectorRegistry(namespace='prometheus_express') metric_beat = Counter('system_heartbeat', 'system heartbeat counter', registry=registry) metric_cpu = Gauge('system_cpu_frequency', 'system CPU frequency', registry=registry) metric_alloc = Gauge('system_memory_alloc', 'allocated system memory', registry=registry) metric_free = Gauge('system_memory_free', 'free system memory', registry=registry) metric_humidity = Gauge('sensor_humidity', 'humidity data from the sensors', labels=['location', 'sensor'], registry=registry) metric_moisture = Gauge('sensor_moisture', 'moisture data from the sensors', labels=['location', 'sensor'], registry=registry) metric_temp = Gauge('sensor_temperature', 'temperature data from the sensors', labels=['location', 'sensor'], registry=registry) def sample_sensors(t): # update metrics metric_alloc.set(gc.mem_alloc()) metric_beat.inc(1) metric_cpu.set(machine.freq()) metric_free.set(gc.mem_free()) # sample sensors bme_reading = bme.read_compensated_data() esp_reading = esp32.raw_temperature() stemma_reading = ss.moisture_read() location = config['metric_location'] metric_humidity.labels(location, 'bme280').set(bme_reading[2]) metric_moisture.labels(location, 'stemma').set(stemma_reading) metric_temp.labels(location, 'esp32').set(temp_ftoc(esp_reading)) metric_temp.labels(location, 'bme280').set(bme_reading[0]) metric_temp.labels(location, 'stemma').set(ss.get_temp()) # scale & buffer last reading sl.push(scale(bme_reading[0], 16, 24)) # update display display_moisture = stemma_reading display_temp = bme_reading[0] oled.fill(0x0) sl.draw(oled, 0, 16) oled.text('{:04.2f}'.format(display_temp), 0, 0) oled.text('{:04.2f}'.format(display_moisture), 64, 0) oled.show() # endregion # setup HTTP routing #region: routing def authenticate(headers, body): print('authenticating:', headers, body) return None def config_read(headers, body): return response('{}'.format(config)) router = Router() router.register('GET', '/boot', bind_middleware(boot_read, [authenticate])) router.register('PUT', '/boot', bind_middleware(boot_write, [authenticate])) router.register('GET', '/config', bind_middleware(config_read, [authenticate])) router.register('GET', '/metrics', registry.handler) server = False # endregion # main server loop timer = machine.Timer(-1) timer.init(period=5000, mode=machine.Timer.PERIODIC, callback=sample_sensors) while True: while not eth_check(eth): print('Waiting for ethernet connection...') time.sleep(1) while not server: print('Attempting to bind server...') time.sleep(1) server = bind(eth, config) # wait for request try: server.accept(router) except OSError as err: print('Error accepting request: {}'.format(err)) except ValueError as err: print('Error parsing request: {}'.format(err))
esp.osdebug(None) except: pass try: import pyb pyb.country("US") # ISO 3166-1 Alpha-2 code, eg US, GB, DE, AU pyb.usb_mode("VCP+MSC") # act as a serial and a storage device # pyb.main('main.py') # main script to run after this one # pyb.usb_mode('VCP+HID') # act as a serial device and a mouse except: pass SD = False if SD: # Mount SD to /sd try: # Some boards have pulldown and/or LED on GPIO2, pullup avoids issues on TTGO 8 v1.8 # machine.Pin(2,mode=machine.Pin.IN, pull=machine.Pin.PULL_UP) # os.mount(machine.SDCard(slot=1, width=4), "/sd") # SD mode 4 bit if esp: # # SPI 1 bit M5Stack Core os.mount( machine.SDCard(slot=2, width=1, sck=18, miso=19, mosi=23, cs=4), "/sd") # SPI 1 bit M5Stack Core print("SD Card mounted") except OSError as e: if e.args[0] == 16: print("No SD Card found")
import esp import machine import uos import ujson import utime # disable os debug info esp.osdebug(None) # initialize and mount SD card, the front end GUI is stored in SD card try: # try to mount SD card using MMC interface # for TTGO T8 some external 10K resistors are needed # see: https://github.com/micropython/micropython/issues/4722 sd = machine.SDCard() uos.mount(sd, '/sd') except Exception as e: # otherwise mount SD card using SPI print( 'Failed to mount the SD card using MMC, now attempting to mount with SPI.' ) try: sd = machine.SDCard(slot=2, mosi=15, miso=2, sck=14, cs=13) uos.mount(sd, '/sd') except Exception as e: print('Failed to mount the SD with SPI.') print('--------------------') else: print('SD Card initialized and mounted') print('--------------------')
import machine import uos as os sd = machine.SDCard(slot=2, width=1, sck=18, cs=4, mosi=23, miso=19) os.mount(sd, '/sd') os.chdir('/sd') print(os.listdir())
def main(): # setup sensors bus = machine.I2C(scl=machine.Pin(16), sda=machine.Pin(13)) bme = BME280(i2c=bus) oled = SSD1306_I2C(128, 32, bus) # setup storage card = machine.SDCard() os.mount(card, '/card') # setup networking config = load_config('/card', 'config.yml') eth = eth_start(config, mdc=machine.Pin(23), mdio=machine.Pin(18), phy_type=network.PHY_LAN8720, phy_addr=0, clock_mode=network.ETH_CLOCK_GPIO17_OUT, power_pin=machine.Pin(12, machine.Pin.OUT)) # setup display sl = Sparkline(32, 128) oled.init_display() oled.fill(0x0) oled.text('loading', 0, 0) oled.show() # setup Prometheus metrics registry = CollectorRegistry(namespace='prometheus_express') metric_beat = Counter('system_heartbeat', 'system heartbeat counter', labels=['location'], registry=registry) metric_temp = Gauge('sensor_temperature', 'temperature data from the sensors', labels=['location', 'sensor'], registry=registry) router = Router() router.register('GET', '/metrics', registry.handler) server = False # wait for incoming connection while True: while not server: time.sleep(1) server = bind(eth, config) bme_reading = bme.read_compensated_data() temp_line = ((bme_reading[0] - 12) * 2) % 32 print('temp line: {}'.format(temp_line)) oled.fill(0x0) sl.push(temp_line) sl.draw(oled, 0, 12) oled.text(str(bme_reading[0]), 0, 0) oled.show() location = config['metric_location'] metric_beat.labels(location).inc(1) metric_temp.labels(location, 'esp32').set(temp_ftoc(esp32.raw_temperature())) metric_temp.labels(location, 'bme280').set(bme_reading[0]) try: server.accept(router) except OSError as err: print('Error accepting request: {}'.format(err)) except ValueError as err: print('Error parsing request: {}'.format(err))
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
import machine from machine import Pin import camera import time flash = Pin(4, Pin.OUT) flash.value(1) time.sleep(1) flash.value(0) uos.mount(machine.SDCard(), "/sd") #mount the SD card camera.init() camera.quality(10) camera.framesize(9) count = 0 while True: if count == 2200: print("Completed") break flash.value(1) pic = camera.capture() flash.value(0) file = open("/sd/pics/" + str(count) + ".jpg", "wb") file.write(pic) file.close() print(count, " done") count += 1 time.sleep(1) print("done")
# Complete project details at https://RandomNerdTutorials.com try: import pca9865 SDA = 16 SCL = 0 drive = pca9865.pca9865(SDA, SCL) drive.alloff() except: pass import machine import uos try: uos.mount(machine.SDCard(slot=1), "/sd") except: pass import machine p = machine.Pin(13, machine.Pin.OUT) p.value(0) import webrepl webrepl.start() import network import esp