示例#1
0
def mount(location='/sd'):
    print('Setting up SD card')
    spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
    cs = digitalio.DigitalInOut(board.SD_CS)
    sdcard = adafruit_sdcard.SDCard(spi, cs)
    vfs = storage.VfsFat(sdcard)
    storage.mount(vfs, location)
示例#2
0
def mount_sd():
    """Mount the SD card"""
    spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
    sd_cs = digitalio.DigitalInOut(board.SD_CS)
    sdcard = adafruit_sdcard.SDCard(spi, sd_cs, baudrate=6000000)
    vfs = storage.VfsFat(sdcard)
    storage.mount(vfs, "/sd")
示例#3
0
    def __init__(self, spi=None, cs=None, dc=None, ts_cs=None, sd_cs=None):
        displayio.release_displays()
        if spi is None:
            spi = board.SPI()
        if cs is None:
            cs = board.D9
        if dc is None:
            dc = board.D10

        if ts_cs is None:
            ts_cs = board.D6
        if sd_cs is None:
            sd_cs = board.D5

        ts_cs = digitalio.DigitalInOut(ts_cs)

        self._display_bus = displayio.FourWire(spi, command=dc, chip_select=cs)

        self._sdcard = None
        try:
            self._sdcard = sdcardio.SDCard(spi, sd_cs)
            vfs = storage.VfsFat(self._sdcard)
            storage.mount(vfs, "/sd")
        except OSError as error:
            print("No SD card found:", error)

        try:
            # the screen might not be ready from cold boot
            time.sleep(0.8)
            self.touchscreen = Adafruit_STMPE610_SPI(spi, ts_cs)
        except RuntimeError:
            # wait and try once more
            time.sleep(1.0)
            self.touchscreen = Adafruit_STMPE610_SPI(spi, ts_cs)
示例#4
0
    def __init__(self, spi=None, cs=None, dc=None, i2c=None):
        displayio.release_displays()
        if spi is None:
            spi = board.SPI()
        if cs is None:
            cs = board.D9
        if dc is None:
            dc = board.D10
        if i2c is None:
            i2c = board.I2C()

        ts_cs = digitalio.DigitalInOut(board.D6)
        self.touchscreen = Adafruit_STMPE610_SPI(spi, ts_cs)

        display_bus = displayio.FourWire(spi, command=dc, chip_select=cs)
        self.display = adafruit_ili9341.ILI9341(display_bus, width=320, height=240)
        self.neopixel = neopixel.NeoPixel(board.D11, 1)
        self.keyboard = BBQ10Keyboard(i2c)
        sd_cs = board.D5
        self._sdcard = None
        try:
            self._sdcard = sdcardio.SDCard(spi, sd_cs)
            vfs = storage.VfsFat(self._sdcard)
            storage.mount(vfs, "/sd")
        except OSError as error:
            print("No SD card found:", error)
示例#5
0
def save():
    spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
    cs = digitalio.DigitalInOut(board.SD_CS)
    sdcard = adafruit_sdcard.SDCard(spi, cs)
    vfs = storage.VfsFat(sdcard)
    storage.mount(vfs, "/sd")
    save_pixels("/sd/splot.bmp")
示例#6
0
    def __init__(self):
        """
        Big init routine as the whole board is brought up.
        """
        self.hardware = {
            'SDcard': False,
            'ESP32': False,
            'Neopixel': False,
        }
        self.payload = None
        self.filename = ''
        # Define LEDs:
        self._led = digitalio.DigitalInOut(board.LED)
        self._led.switch_to_output()

        # Define battery voltage
        # self._vbatt = analogio.AnalogIn(board.BATTERY)

        # Define SPI,I2C,UART
        self._spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
        self._uart = busio.UART(board.TX2, board.RX2)

        # Define sdcard
        self._sdcs = digitalio.DigitalInOut(board.xSDCS)
        self._sdcs.direction = digitalio.Direction.OUTPUT
        self._sdcs.value = True

        # Initialize sdcard
        try:
            import adafruit_sdcard
            self._sd = adafruit_sdcard.SDCard(self._spi, self._sdcs)
            self._vfs = storage.VfsFat(self._sd)
            storage.mount(self._vfs, "/sd")
            sys.path.append("/sd")
            self.hardware['SDcard'] = True
        except Exception as e:
            print('[WARNING]', e)

        # Define ESP32
        self._esp_dtr = digitalio.DigitalInOut(board.DTR)
        self._esp_rts = digitalio.DigitalInOut(board.RTS)
        self._esp_cs = digitalio.DigitalInOut(board.TMS)  #GPIO14
        self._esp_rdy = digitalio.DigitalInOut(board.TCK)  #GPIO13
        self._esp_cs.direction = digitalio.Direction.OUTPUT
        self._esp_dtr.direction = digitalio.Direction.OUTPUT
        self._esp_rts.direction = digitalio.Direction.OUTPUT
        self._esp_cs.value = True
        self._esp_dtr.value = False
        self._esp_rts.value = False

        # Initialize Neopixel
        try:
            self.neopixel = neopixel.NeoPixel(board.NEOPIXEL,
                                              1,
                                              brightness=0.2,
                                              pixel_order=neopixel.GRB)
            self.neopixel[0] = (0, 0, 0)
            self.hardware['Neopixel'] = True
        except Exception as e:
            print('[WARNING]', e)
 def setup_sd(self, sdcs):
     try:
         self.sdcard = sdcardio.SDCard(self.sp, sdcs)
     except OSError:
         return False
     self.vfs = storage.VfsFat(self.sdcard)
     storage.mount(self.vfs, "/sd")
     return True
示例#8
0
def save():
    spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
    cs = digitalio.DigitalInOut(board.SD_CS)
    sdcard = adafruit_sdcard.SDCard(spi, cs)
    vfs = storage.VfsFat(sdcard)
    storage.mount(vfs, "/sd")

    print("Taking Screenshot...")
    save_pixels("/sd/screenshot.bmp")
    print("Screenshot taken")
示例#9
0
    def __init__(self, spi, i2c):
        cs = digitalio.DigitalInOut(board.D10)
        sdcard = adafruit_sdcard.SDCard(spi, cs)
        vfs = storage.VfsFat(sdcard)
        storage.mount(vfs, '/sd')

        # Location on the sd-card where the information is saved
        self.pressure_path = '/sd/pressure.txt'

        # The storage unit responsible for time
        self.rtc = adafruit_pcf8523.PCF8523(i2c)
示例#10
0
def mount_device( request ):
    """Mount a USB device; wrapper around storage.mount().
    """
    if request.method == 'POST':
        mount_form = MountForm(request.POST, devices=unmounted_devices())
        if mount_form.is_valid():
            raw = mount_form.cleaned_data['device']
            devicefile,label = raw.split(' ',1)
            mount(request, devicefile, label)
            # TODO regenerate redis caches
    return HttpResponseRedirect( reverse('storage-index') )
示例#11
0
def _main():
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger()

    storage.mount()
    time.sleep(1)
    storage.sync()
    time.sleep(1)
    storage.umount()
    configfs.clean()

    return 0
示例#12
0
    def __init__(self):
        # Set up watchdog timer
        self.watchdog = microcontroller.watchdog
        self.watchdog.deinit()
        self.watchdog.timeout = WATCHDOG_TIMEOUT
        self.watchdog.mode = WATCHDOG_MODE

        # Set up heartbeat output (i.e red LED)
        self._heartbeat = digitalio.DigitalInOut(HEARTBEAT_PIN)
        self._heartbeat.direction = digitalio.Direction.OUTPUT
        self._heartbeat_duration = HEARTBEAT_DURATION

        # Set up I2C bus
        i2c = busio.I2C(board.SCL, board.SDA)
        # Set up SPI bus
        spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

        # Set up real time clock as source for time.time() or time.localtime() calls.
        print("Initialising real time clock.\n\n\n\n")
        clock = PCF8523(i2c)
        rtc.set_time_source(clock)

        print("Initialising display.\n\n\n\n")
        self.display = Display(self, DISPLAY_TIMEOUT, i2c, spi)

        print("Initialising lights.\n\n\n\n")
        self.lights = Lights(LIGHTS_ON_TIME, LIGHTS_OFF_TIME, LIGHTS_ENABLE_PIN, LIGHTS_DISABLE_PIN)

        print("Initialising feeder.\n\n\n\n")
        self.feeder = Feeder(FEEDING_TIMES, PORTIONS_PER_MEAL, FEEDER_MOTOR, FEEDER_STEPS_PER_ROTATION,
                             FEEDER_STEP_DELAY, FEEDER_STEP_STYLE, i2c)

        print("Initialising temperature sensors.\n\n\n\n")
        ow_bus = OneWireBus(OW_PIN)
        self.water_sensor = TemperatureSensor(ow_bus, WATER_SN, WATER_OFFSET)
        self.air_sensor = TemperatureSensor(ow_bus, AIR_SN, AIR_OFFSET)

        # Set up SD card
        print("Setting up logging.\n\n\n\n")
        cs = digitalio.DigitalInOut(SD_CS)
        sdcard = SDCard(spi, cs)
        vfs = storage.VfsFat(sdcard)
        storage.mount(vfs, "/sd")
        self._log_data = LOG_DATA
        self._log_interval = time_tuple_to_secs(LOG_INTERVAL)
        self._last_log = None

        print("Initialising Bluetooth.\n\n\n\n")
        self._ble = BLERadio()
        self._ble._adapter.name = BLE_NAME
        self._ble_uart = UARTService()
        self._ble_ad = ProvideServicesAdvertisement(self._ble_uart)
示例#13
0
def mountspi():
    import board,os,storage
    from busio import SPI
    from digitalio import DigitalInOut

    spi = SPI(board.A5,board.A7,board.A6)
    cs = DigitalInOut(board.A0)
    flash = SPIFlash(spi,cs)
    bdev = SPIFlashBlockDevice(flash,nblocks=2048,debug=False)
    try:
        vfs = storage.VfsFat(bdev)
        vfs.ilistdir('/')
    except OSError:
        print("Formatting device")
        storage.VfsFat.mkfs(bdev)
        vfs = storage.VfsFat(bdev)
    storage.mount(vfs,"/spi")
示例#14
0
def setup_sd(mountpoint='/sd'):
    import adafruit_sdcard
    import storage
    try:
        spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
        cs = digitalio.DigitalInOut(board.SD_CS)
        sdcard = adafruit_sdcard.SDCard(spi, cs)
        vfs = storage.VfsFat(sdcard)
        storage.mount(vfs, mountpoint)
        print('Found SD card.')
        blink_led(gled, .075, 5)
        return sdcard, vfs
    except Exception as e:
        print('Failed to set up and mount SD card! Exception info:', str(e),
              '\nPrinting to console instead.')
        blink_led(rled, .075, 5)
        return None, None
示例#15
0
def setup():
    check_bootsec()
    print("Performing initial setup")
    wifi()
    storage.VfsFat.mkfs(bdev)
    vfs = storage.VfsFat(bdev)
    storage.mount(vfs, '/')
    with open("boot.py", "w") as f:
        f.write("""\
# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
import gc
#import webrepl
#webrepl.start()
gc.collect()
""")
    return vfs
示例#16
0
def _main():

    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger()
    logger.info(f'Started mass storage gadget synchronizer')

    configfs.clean()
    configfs.define()
    logger.info(f'Defined zero gadget with mass storage')

    storage.mount()
    logger.info(f'Mounted storage "{storage.WATCH_PATH}"')

    try:
        while True:
            storage.sync()
            logger.debug(f'Storage synch 1 "{storage.WATCH_PATH}" for update')
            time.sleep(1)

            storage.umount()
            logger.debug(
                f'Storage unmounted "{storage.WATCH_PATH}" for update')
            time.sleep(1)

            storage.sync()
            logger.debug(f'Storage synch 2 "{storage.WATCH_PATH}" for update')
            time.sleep(1)

            storage.mount()
            logger.debug(f'Storage mounted "{storage.WATCH_PATH}" for update')

            logger.info(
                f'Synced storage "{storage.WATCH_PATH}" with mass storage')

            time.sleep(60)

    except KeyboardInterrupt:
        storage.sync()
        storage.umount()
        logger.info(f'Storage unmounted "{storage.WATCH_PATH}"')
        configfs.clean()
        logger.info(f'Cleaned mass storage gadget')

    return 0
示例#17
0
def remount1( request ):
    """
    NOTES:
    Storage device's device file, label, and mount_path are stored in session
    on mount and removed from session on unmount.
    When the VM is suspended and resumed, the device often becomes available
    with a different device file (i.e. /dev/sdc1 instead of /dev/sdb1).
    The device is still "mounted" with the old device file.
    We need to unmount from the old device file and remount with the new
    device file that we get from looking directly at the system's device info.
    """
    remount_uri = request.session.get(settings.REDIRECT_URL_SESSION_KEY, None)
    # device label
    label = request.session.get('storage_label', None)
    # current "mounted" devicefile
    devicefile_session = request.session.get('storage_devicefile', None)
    # the actual new devicefile
    devicefile_udisks = None
    if label:
        for d in removables():
            if d['label'] == label:
                devicefile_udisks = d['devicefile']
    # unmount, mount
    unmounted,mount_path = None,None
    remount_attempted = False
    if devicefile_session and label and devicefile_udisks:
        unmounted = unmount(request, devicefile_session, label)
        mount_path = mount(request, devicefile_udisks, label)
        remount_attempted = True
    else:
        messages.warning(request, STORAGE_MESSAGES['REMOUNT_FAIL'])
    # redirect
    url = reverse('storage-index')
    if remount_attempted and mount_path:
        url = remount_uri
        if url and (not url.find('remount') > -1):
            del request.session[settings.REDIRECT_URL_SESSION_KEY]
    # just to be sure we have a url...
    if not url:
        url = reverse('storage-index')
    return redirect(url)
示例#18
0
    def __init__(self,
                 *,
                 url=None,
                 json_path=None,
                 regexp_path=None,
                 default_bg=0x000000,
                 status_neopixel=None,
                 text_font=None,
                 text_position=None,
                 text_color=0x808080,
                 text_wrap=False,
                 text_maxlen=0,
                 text_transform=None,
                 image_json_path=None,
                 image_resize=None,
                 image_position=None,
                 caption_text=None,
                 caption_font=None,
                 caption_position=None,
                 caption_color=0x808080,
                 success_callback=None,
                 debug=False):

        self._debug = debug

        try:
            self._backlight = pulseio.PWMOut(board.TFT_BACKLIGHT)  # pylint: disable=no-member
        except ValueError:
            self._backlight = None
        self.set_backlight(1.0)  # turn on backlight

        self._url = url
        if json_path:
            if isinstance(json_path[0], (list, tuple)):
                self._json_path = json_path
            else:
                self._json_path = (json_path, )
        else:
            self._json_path = None

        self._regexp_path = regexp_path
        self._success_callback = success_callback

        if status_neopixel:
            self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2)
        else:
            self.neopix = None
        self.neo_status(0)

        try:
            os.stat(LOCALFILE)
            self._uselocal = True
        except OSError:
            self._uselocal = False

        if self._debug:
            print("Init display")
        self.splash = displayio.Group(max_size=15)

        if self._debug:
            print("Init background")
        self._bg_group = displayio.Group(max_size=1)
        self._bg_file = None
        self._default_bg = default_bg
        self.splash.append(self._bg_group)

        # show thank you and bootup file if available
        for bootscreen in ("/thankyou.bmp", "/pyportal_startup.bmp"):
            try:
                os.stat(bootscreen)
                board.DISPLAY.show(self.splash)
                for i in range(100, -1, -1):  # dim down
                    self.set_backlight(i / 100)
                    time.sleep(0.005)
                self.set_background(bootscreen)
                board.DISPLAY.wait_for_frame()
                for i in range(100):  # dim up
                    self.set_backlight(i / 100)
                    time.sleep(0.005)
                time.sleep(2)
            except OSError:
                pass  # they removed it, skip!

        self._speaker_enable = DigitalInOut(board.SPEAKER_ENABLE)
        self._speaker_enable.switch_to_output(False)
        self.audio = audioio.AudioOut(board.AUDIO_OUT)
        try:
            self.play_file("pyportal_startup.wav")
        except OSError:
            pass  # they deleted the file, no biggie!

        # Make ESP32 connection
        if self._debug:
            print("Init ESP32")
        esp32_ready = DigitalInOut(board.ESP_BUSY)
        esp32_gpio0 = DigitalInOut(board.ESP_GPIO0)
        esp32_reset = DigitalInOut(board.ESP_RESET)
        esp32_cs = DigitalInOut(board.ESP_CS)
        spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

        self._esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs,
                                                     esp32_ready, esp32_reset,
                                                     esp32_gpio0)
        #self._esp._debug = 1
        for _ in range(3):  # retries
            try:
                print("ESP firmware:", self._esp.firmware_version)
                break
            except RuntimeError:
                print("Retrying ESP32 connection")
                time.sleep(1)
                self._esp.reset()
        else:
            raise RuntimeError("Was not able to find ESP32")
        requests.set_interface(self._esp)

        if url and not self._uselocal:
            self._connect_esp()

        # set the default background
        self.set_background(self._default_bg)
        board.DISPLAY.show(self.splash)

        if self._debug:
            print("Init SD Card")
        sd_cs = DigitalInOut(board.SD_CS)
        self._sdcard = None
        try:
            self._sdcard = adafruit_sdcard.SDCard(spi, sd_cs)
            vfs = storage.VfsFat(self._sdcard)
            storage.mount(vfs, "/sd")
        except OSError as error:
            print("No SD card found:", error)

        self._qr_group = None

        if self._debug:
            print("Init caption")
        self._caption = None
        if caption_font:
            self._caption_font = bitmap_font.load_font(caption_font)
        self.set_caption(caption_text, caption_position, caption_color)

        if text_font:
            if isinstance(text_position[0], (list, tuple)):
                num = len(text_position)
                if not text_wrap:
                    text_wrap = [0] * num
                if not text_maxlen:
                    text_maxlen = [0] * num
                if not text_transform:
                    text_transform = [None] * num
            else:
                num = 1
                text_position = (text_position, )
                text_color = (text_color, )
                text_wrap = (text_wrap, )
                text_maxlen = (text_maxlen, )
                text_transform = (text_transform, )
            self._text = [None] * num
            self._text_color = [None] * num
            self._text_position = [None] * num
            self._text_wrap = [None] * num
            self._text_maxlen = [None] * num
            self._text_transform = [None] * num
            self._text_font = bitmap_font.load_font(text_font)
            if self._debug:
                print("Loading font glyphs")
            # self._text_font.load_glyphs(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
            #                             b'0123456789:/-_,. ')
            gc.collect()

            for i in range(num):
                if self._debug:
                    print("Init text area", i)
                self._text[i] = None
                self._text_color[i] = text_color[i]
                self._text_position[i] = text_position[i]
                self._text_wrap[i] = text_wrap[i]
                self._text_maxlen[i] = text_maxlen[i]
                self._text_transform[i] = text_transform[i]
        else:
            self._text_font = None
            self._text = None

        self._image_json_path = image_json_path
        self._image_resize = image_resize
        self._image_position = image_position
        if image_json_path:
            if self._debug:
                print("Init image path")
            if not self._image_position:
                self._image_position = (0, 0)  # default to top corner
            if not self._image_resize:
                self._image_resize = (320, 240)  # default to full screen

        if self._debug:
            print("Init touchscreen")
        # pylint: disable=no-member
        self.touchscreen = adafruit_touchscreen.Touchscreen(
            board.TOUCH_XL,
            board.TOUCH_XR,
            board.TOUCH_YD,
            board.TOUCH_YU,
            calibration=((5200, 59000), (5800, 57000)),
            size=(320, 240))
        # pylint: enable=no-member

        self.set_backlight(1.0)  # turn on backlight

        gc.collect()
示例#19
0
    def __init__(self, spi, display, splash_group, debug=False):
        # Speaker Enable
        self._speaker_enable = DigitalInOut(board.SPEAKER_ENABLE)
        self._speaker_enable.switch_to_output(False)

        self._display = display

        if hasattr(board, "AUDIO_OUT"):
            self.audio = audioio.AudioOut(board.AUDIO_OUT)
        elif hasattr(board, "SPEAKER"):
            self.audio = audioio.AudioOut(board.SPEAKER)
        else:
            raise AttributeError("Board does not have a builtin speaker!")

        if debug:
            print("Init SD Card")
        sd_cs = board.SD_CS
        if not NATIVE_SD:
            sd_cs = DigitalInOut(sd_cs)
        self._sdcard = None

        try:
            self._sdcard = sdcardio.SDCard(spi, sd_cs)
            vfs = storage.VfsFat(self._sdcard)
            storage.mount(vfs, "/sd")
        except OSError as error:
            print("No SD card found:", error)

        try:
            if hasattr(board, "TFT_BACKLIGHT"):
                self._backlight = pulseio.PWMOut(board.TFT_BACKLIGHT)  # pylint: disable=no-member
            elif hasattr(board, "TFT_LITE"):
                self._backlight = pulseio.PWMOut(board.TFT_LITE)  # pylint: disable=no-member
        except ValueError:
            self._backlight = None
        self.set_backlight(1.0)  # turn on backlight
        # pylint: disable=import-outside-toplevel
        if hasattr(board, "TOUCH_XL"):
            import adafruit_touchscreen

            if debug:
                print("Init touchscreen")
            # pylint: disable=no-member
            self.touchscreen = adafruit_touchscreen.Touchscreen(
                board.TOUCH_XL,
                board.TOUCH_XR,
                board.TOUCH_YD,
                board.TOUCH_YU,
                calibration=((5200, 59000), (5800, 57000)),
                size=(board.DISPLAY.width, board.DISPLAY.height),
            )
            # pylint: enable=no-member

            self.set_backlight(1.0)  # turn on backlight
        elif hasattr(board, "BUTTON_CLOCK"):
            from adafruit_cursorcontrol.cursorcontrol import Cursor
            from adafruit_cursorcontrol.cursorcontrol_cursormanager import CursorManager

            if debug:
                print("Init cursor")
            self.mouse_cursor = Cursor(board.DISPLAY,
                                       display_group=splash_group,
                                       cursor_speed=8)
            self.mouse_cursor.hide()
            self.cursor = CursorManager(self.mouse_cursor)
        else:
            raise AttributeError(
                "PyPortal module requires either a touchscreen or gamepad.")
        # pylint: enable=import-outside-toplevel

        gc.collect()
示例#20
0
# setup display
displayio.release_displays()
tft_cs = board.D9
tft_dc = board.D10
display_bus = displayio.FourWire(spi, command=tft_dc, chip_select=tft_cs)
display = adafruit_ili9341.ILI9341(display_bus, width=320, height=240)

# setup keyboard
kbd = BBQ10Keyboard(i2c)

# setup microSD
sd_cs = board.D5
sdcard = adafruit_sdcard.SDCard(spi, digitalio.DigitalInOut(sd_cs))
vfs = storage.VfsFat(sdcard)
storage.mount(vfs, '/sd')

# setup NeoPixels
pix0 = neopixel.NeoPixel(board.NEOPIXEL, 1)
pix0[0] = 0x000080

pix1 = neopixel.NeoPixel(board.D11, 1)

#
while True:
    k = kbd.keys
    for i in k:
        if i[0] == 1:
            print(i[1], end='')
            pix1[0] = 0x000404
        elif i[0] == 3:
示例#21
0
def check_SDCARD():

    initialize_OLED()

    LED[10].deinit()
    LED[11].deinit()
    LED[12].deinit()
    LED[15].deinit()
    spi = busio.SPI(board.GP10, MOSI=board.GP11, MISO=board.GP12)
    cs = board.GP15

    try:
        global sd
        sd = sdcardio.SDCard(spi, cs)

        vfs = storage.VfsFat(sd)
        storage.mount(vfs, '/sd')

        with open("/sd/pico.txt", "w") as file:
            file.write("1. Hello, world!\r\n")

        with open("/sd/pico.txt", "r") as file:
            for line in file:
                if line == "1. Hello, world!\r\n":
                    for i in up:
                        buzzer.frequency = tones[i]
                        buzzer.duty_cycle = 19660
                        time.sleep(0.15)
                    buzzer.duty_cycle = 0
                    if I2C:
                        oled.text('GP22 PRESSED', 30, 20, 1)
                        oled.text('SD CARD TEST: PASS', 7, 40, 1)

                else:
                    if I2C:
                        oled.text('GP22 PRESSED', 30, 10, 1)
                        oled.text('SD CARD TEST: FAILED', 5, 25, 1)
                        oled.text('WRONG DATA', 33, 40, 1)
                    buzzer.frequency = 1661
                    buzzer.duty_cycle = 19660
                    time.sleep(2)
                    buzzer.duty_cycle = 0
                    time.sleep(2)
        storage.umount(vfs)
        spi.deinit()
        sd.deinit()
    except:
        if I2C:
            oled.text('GP22 PRESSED', 30, 10, 1)
            oled.text('SD CARD TEST: FAILED', 5, 25, 1)
            oled.text('NO SD CARD', 33, 40, 1)

        buzzer.frequency = 1661
        buzzer.duty_cycle = 19660
        time.sleep(2)
        buzzer.duty_cycle = 0
        spi.deinit()
    if I2C:
        deinitialize_OLED()

    LED[10] = digitalio.DigitalInOut(board.GP10)
    LED[10].direction = digitalio.Direction.OUTPUT
    LED[11] = digitalio.DigitalInOut(board.GP11)
    LED[11].direction = digitalio.Direction.OUTPUT
    LED[12] = digitalio.DigitalInOut(board.GP12)
    LED[12].direction = digitalio.Direction.OUTPUT
    LED[15] = digitalio.DigitalInOut(board.GP15)
    LED[15].direction = digitalio.Direction.OUTPUT
示例#22
0
def takeimage():
    # Configuration:
    SD_CS_PIN = board.D10  # CS for SD card (SD_CS is for Feather Adalogger)
    IMAGE_FILE = '/sd/image.jpg'  # Full path to file name to save captured image.
    # Will overwrite!

    # Setup SPI bus (hardware SPI).
    spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)

    # Setup SD card and mount it in the filesystem.
    sd_cs = digitalio.DigitalInOut(SD_CS_PIN)
    sdcard = adafruit_sdcard.SDCard(spi, sd_cs)
    vfs = storage.VfsFat(sdcard)
    storage.mount(vfs, '/sd')

    # Create a serial connection for the VC0706 connection, speed is auto-detected.
    uart = busio.UART(board.TX, board.RX, timeout=250)
    # Setup VC0706 camera
    vc0706 = adafruit_vc0706.VC0706(uart)

    # Print the version string from the camera.
    print('VC0706 version:')
    print(vc0706.version)

    # Set the baud rate to 115200 for fastest transfer (its the max speed)
    vc0706.baudrate = 115200

    # Set the image size.
    vc0706.image_size = adafruit_vc0706.IMAGE_SIZE_640x480  # Or set IMAGE_SIZE_320x240 or
    # IMAGE_SIZE_160x120
    # Note you can also read the property and compare against those values to
    # see the current size:
    # size = vc0706.image_size
    # if size == adafruit_vc0706.IMAGE_SIZE_640x480:
    #     print('Using 640x480 size image.')
    # elif size == adafruit_vc0706.IMAGE_SIZE_320x240:
    #     print('Using 320x240 size image.')
    # elif size == adafruit_vc0706.IMAGE_SIZE_160x120:
    #     print('Using 160x120 size image.')

    # Take a picture.
    print('Taking a picture in 3 seconds...')
    time.sleep(3)
    print('SNAP!')
    if not vc0706.take_picture():
        raise RuntimeError('Failed to take picture!')

    # Print size of picture in bytes.
    frame_length = vc0706.frame_length
    print('Picture size (bytes): {}'.format(frame_length))

    # Open a file for writing (overwriting it if necessary).
    # This will write 50 bytes at a time using a small buffer.
    # You MUST keep the buffer size under 100!
    print('Writing image: {}'.format(IMAGE_FILE), end='')
    with open(IMAGE_FILE, 'wb') as outfile:
        wcount = 0
        while frame_length > 0:
            # Compute how much data is left to read as the lesser of remaining bytes
            # or the copy buffer size (32 bytes at a time).  Buffer size MUST be
            # a multiple of 4 and under 100.  Stick with 32!
            to_read = min(frame_length, 32)
            copy_buffer = bytearray(to_read)
            # Read picture data into the copy buffer.
            if vc0706.read_picture_into(copy_buffer) == 0:
                raise RuntimeError('Failed to read picture frame data!')
            # Write the data to SD card file and decrement remaining bytes.
            outfile.write(copy_buffer)
            frame_length -= 32
            # Print a dot every 2k bytes to show progress.
            wcount += 1
            if wcount >= 64:
                print('.', end='')
                wcount = 0
    print("")
    print('Finished!')
示例#23
0
def run_tests(board, binary, tests, log_key=None):
    serial_device_name = None
    for port in list_ports.comports():
        if port.location and port.location[2:] == board["path"]:
            serial_device_name = port.name
    if not serial_device_name:
        raise RuntimeError("Board not found at path: " + board["path"])

    bootloader = board["bootloader"]
    tests_ok = True

    with redis.lock("lock:device@" + board["path"], timeout=60 * 20) as lock:
        # Trigger the bootloader.
        if bootloader in ("uf2", "samba"):
            s = serial.Serial("/dev/" + serial_device_name,
                              1200,
                              write_timeout=4,
                              timeout=4)
            s.close()

        time.sleep(5)

        if bootloader == "uf2":
            # Mount the filesystem.
            disk_path = None
            for disk in os.listdir("/dev/disk/by-path"):
                if board["path"] in disk:
                    disk_path = disk
            if not disk_path:
                raise RuntimeError("Disk not found for board: " +
                                   board["path"])

            disk_path = "/dev/disk/by-path/" + disk_path
            if os.path.isfile(disk_path + "-part1"):
                raise RuntimeError(
                    "MCU not in bootloader because part1 exists.")

            sh.pmount(disk_path, "fs-" + board["path"])
            mountpoint = "/media/fs-" + board["path"]
            redis_log(
                log_key, "Successfully mounted UF2 bootloader at {0}\n".format(
                    mountpoint))
            with open(mountpoint + "/INFO_UF2.TXT", "r") as f:
                redis_log(log_key, f.read() + "\n")
            shutil.copy(binary, mountpoint)
            # Unmount the mountpoint in case the device has disappeared already after the UF2
            # was flashed.
            sh.pumount(mountpoint)

        if "circuitpython_tests" in tests:
            # First find our CircuitPython disk.
            start_time = time.monotonic()
            disk_path = None
            while not disk_path and time.monotonic() - start_time < 10:
                for disk in os.listdir("/dev/disk/by-path"):
                    if board["path"] in disk and disk.endswith("part1"):
                        disk_path = disk
            if not disk_path:
                raise RuntimeError("Cannot find CIRCUITPY disk for device: " +
                                   board["path"])

            disk_path = "/dev/disk/by-path/" + disk_path
            disk_device = os.path.basename(os.readlink(disk_path))[:-1]

            with storage.mount(storage.NativeFileSystem(disk_path),
                               "/media/cpy-" + board["path"]):
                mountpoint = "/media/cpy-" + board["path"]
                redis_log(
                    log_key,
                    "Successfully mounted CIRCUITPY disk at {0}\n".format(
                        mountpoint))

                # Now find the serial.
                serial_device_name = None
                for port in list_ports.comports():
                    if port.location and port.location[2:] == board["path"]:
                        serial_device_name = port.name
                if not serial_device_name:
                    raise RuntimeError(
                        "No CircuitPython serial connection found at path: " +
                        board["path"])
                with serial.Serial("/dev/" + serial_device_name,
                                   write_timeout=4,
                                   timeout=4) as conn:
                    tests_ok = run_circuitpython_tests(
                        log_key, board["board"], board["test_env"], mountpoint,
                        disk_device, conn,
                        tests["circuitpython_tests"]) and tests_ok

    return tests_ok
    def __init__(self):
        """
        Big init routine as the whole board is brought up.
        """
        self.BOOTTIME = const(time.time())
        self.data_cache = {}
        self.filenumbers = {}
        self.vlowbatt = 6.0
        self.send_buff = memoryview(SEND_BUFF)
        self.debug = True
        self.micro = microcontroller
        self.hardware = {
            'IMU': False,
            'Radio1': False,
            'Radio2': False,
            'SDcard': False,
            'GPS': False,
            'WDT': False,
            'USB': False,
            'PWR': False
        }
        # Define burn wires:
        self._relayA = digitalio.DigitalInOut(board.RELAY_A)
        self._relayA.switch_to_output(
            drive_mode=digitalio.DriveMode.OPEN_DRAIN)
        self._resetReg = digitalio.DigitalInOut(board.VBUS_RST)
        self._resetReg.switch_to_output(
            drive_mode=digitalio.DriveMode.OPEN_DRAIN)

        # Define battery voltage
        self._vbatt = AnalogIn(board.BATTERY)

        # Define MPPT charge current measurement
        self._ichrg = AnalogIn(board.L1PROG)
        self._chrg = digitalio.DigitalInOut(board.CHRG)
        self._chrg.switch_to_input()

        # Define SPI,I2C,UART
        self.i2c1 = busio.I2C(board.SCL, board.SDA)
        self.spi = board.SPI()
        self.uart = busio.UART(board.TX, board.RX)

        # Define GPS
        self.en_gps = digitalio.DigitalInOut(board.EN_GPS)
        self.en_gps.switch_to_output()

        # Define filesystem stuff
        self.logfile = "/log.txt"

        # Define radio
        _rf_cs1 = digitalio.DigitalInOut(board.RF1_CS)
        _rf_rst1 = digitalio.DigitalInOut(board.RF1_RST)
        self.enable_rf = digitalio.DigitalInOut(board.EN_RF)
        self.radio1_DIO0 = digitalio.DigitalInOut(board.RF1_IO0)
        # self.enable_rf.switch_to_output(value=False) # if U21
        self.enable_rf.switch_to_output(value=True)  # if U7
        _rf_cs1.switch_to_output(value=True)
        _rf_rst1.switch_to_output(value=True)
        self.radio1_DIO0.switch_to_input()

        # Initialize SD card (always init SD before anything else on spi bus)
        try:
            # Baud rate depends on the card, 4MHz should be safe
            _sd = sdcardio.SDCard(self.spi, board.SD_CS, baudrate=4000000)
            _vfs = VfsFat(_sd)
            mount(_vfs, "/sd")
            self.fs = _vfs
            sys.path.append("/sd")
            self.hardware['SDcard'] = True
            self.logfile = "/sd/log.txt"
        except Exception as e:
            if self.debug: print('[ERROR][SD Card]', e)

        # Initialize Neopixel
        try:
            self.neopixel = neopixel.NeoPixel(board.NEOPIXEL,
                                              1,
                                              brightness=0.2,
                                              pixel_order=neopixel.GRB)
            self.neopixel[0] = (0, 0, 0)
            self.hardware['Neopixel'] = True
        except Exception as e:
            if self.debug: print('[WARNING][Neopixel]', e)

        # Initialize USB charger
        try:
            self.usb = bq25883.BQ25883(self.i2c1)
            self.usb.charging = False
            self.usb.wdt = False
            self.usb.led = False
            self.usb.charging_current = 8  #400mA
            self.usb_charging = False
            self.hardware['USB'] = True
        except Exception as e:
            if self.debug: print('[ERROR][USB Charger]', e)

        # Initialize Power Monitor
        try:
            self.pwr = adm1176.ADM1176(self.i2c1)
            self.pwr.sense_resistor = 1
            self.hardware['PWR'] = True
        except Exception as e:
            if self.debug: print('[ERROR][Power Monitor]', e)

        # Initialize IMU
        try:
            self.IMU = bmx160.BMX160_I2C(self.i2c1)
            self.hardware['IMU'] = True
        except Exception as e:
            if self.debug: print('[ERROR][IMU]', e)

        # # Initialize GPS
        # try:
        #     self.gps = GPS(self.uart,debug=False) # still powered off!
        #     self.gps.timeout_handler=self.timeout_handler
        #     self.hardware['GPS'] = True
        # except Exception as e:
        #     if self.debug: print('[ERROR][GPS]',e)

        # Initialize radio #1 - UHF
        try:
            self.radio1 = pycubed_rfm9x.RFM9x(self.spi,
                                              _rf_cs1,
                                              _rf_rst1,
                                              433.0,
                                              code_rate=8,
                                              baudrate=1320000)
            # Default LoRa Modulation Settings
            # Frequency: 433 MHz, SF7, BW125kHz, CR4/8, Preamble=8, CRC=True
            self.radio1.dio0 = self.radio1_DIO0
            self.radio1.enable_crc = True
            self.radio1.ack_delay = 0.2
            self.radio1.sleep()
            self.hardware['Radio1'] = True
        except Exception as e:
            if self.debug: print('[ERROR][RADIO 1]', e)

        # set PyCubed power mode
        self.power_mode = 'normal'
示例#25
0
    def __init__(self,
                 *,
                 url=None,
                 headers=None,
                 json_path=None,
                 regexp_path=None,
                 default_bg=0x000000,
                 status_neopixel=None,
                 text_font=None,
                 text_position=None,
                 text_color=0x808080,
                 text_wrap=False,
                 text_maxlen=0,
                 text_transform=None,
                 json_transform=None,
                 image_json_path=None,
                 image_resize=None,
                 image_position=None,
                 caption_text=None,
                 caption_font=None,
                 caption_position=None,
                 caption_color=0x808080,
                 image_url_path=None,
                 success_callback=None,
                 esp=None,
                 external_spi=None,
                 debug=False):

        self._debug = debug

        try:
            if hasattr(board, 'TFT_BACKLIGHT'):
                self._backlight = pulseio.PWMOut(board.TFT_BACKLIGHT)  # pylint: disable=no-member
            elif hasattr(board, 'TFT_LITE'):
                self._backlight = pulseio.PWMOut(board.TFT_LITE)  # pylint: disable=no-member
        except ValueError:
            self._backlight = None
        self.set_backlight(1.0)  # turn on backlight

        self._url = url
        self._headers = headers
        if json_path:
            if isinstance(json_path[0], (list, tuple)):
                self._json_path = json_path
            else:
                self._json_path = (json_path, )
        else:
            self._json_path = None

        self._regexp_path = regexp_path
        self._success_callback = success_callback

        if status_neopixel:
            self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2)
        else:
            self.neopix = None
        self.neo_status(0)

        try:
            os.stat(LOCALFILE)
            self._uselocal = True
        except OSError:
            self._uselocal = False

        if self._debug:
            print("Init display")
        self.splash = displayio.Group(max_size=15)

        if self._debug:
            print("Init background")
        self._bg_group = displayio.Group(max_size=1)
        self._bg_file = None
        self._default_bg = default_bg
        self.splash.append(self._bg_group)

        # show thank you and bootup file if available
        for bootscreen in ("/thankyou.bmp", "/pyportal_startup.bmp"):
            try:
                os.stat(bootscreen)
                board.DISPLAY.show(self.splash)
                for i in range(100, -1, -1):  # dim down
                    self.set_backlight(i / 100)
                    time.sleep(0.005)
                self.set_background(bootscreen)
                board.DISPLAY.wait_for_frame()
                for i in range(100):  # dim up
                    self.set_backlight(i / 100)
                    time.sleep(0.005)
                time.sleep(2)
            except OSError:
                pass  # they removed it, skip!

        self._speaker_enable = DigitalInOut(board.SPEAKER_ENABLE)
        self._speaker_enable.switch_to_output(False)
        if hasattr(board, 'AUDIO_OUT'):
            self.audio = audioio.AudioOut(board.AUDIO_OUT)
        elif hasattr(board, 'SPEAKER'):
            self.audio = audioio.AudioOut(board.SPEAKER)
        else:
            raise AttributeError('Board does not have a builtin speaker!')
        try:
            self.play_file("pyportal_startup.wav")
        except OSError:
            pass  # they deleted the file, no biggie!

        if esp:  # If there was a passed ESP Object
            if self._debug:
                print("Passed ESP32 to PyPortal")
            self._esp = esp
            if external_spi:  #If SPI Object Passed
                spi = external_spi
            else:  # Else: Make ESP32 connection
                spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
        else:
            if self._debug:
                print("Init ESP32")
            esp32_ready = DigitalInOut(board.ESP_BUSY)
            esp32_gpio0 = DigitalInOut(board.ESP_GPIO0)
            esp32_reset = DigitalInOut(board.ESP_RESET)
            esp32_cs = DigitalInOut(board.ESP_CS)
            spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

            self._esp = adafruit_esp32spi.ESP_SPIcontrol(
                spi, esp32_cs, esp32_ready, esp32_reset, esp32_gpio0)
        #self._esp._debug = 1
        for _ in range(3):  # retries
            try:
                print("ESP firmware:", self._esp.firmware_version)
                break
            except RuntimeError:
                print("Retrying ESP32 connection")
                time.sleep(1)
                self._esp.reset()
        else:
            raise RuntimeError("Was not able to find ESP32")
        requests.set_socket(socket, self._esp)

        if url and not self._uselocal:
            self._connect_esp()

        if self._debug:
            print("My IP address is",
                  self._esp.pretty_ip(self._esp.ip_address))

        # set the default background
        self.set_background(self._default_bg)
        board.DISPLAY.show(self.splash)

        if self._debug:
            print("Init SD Card")
        sd_cs = DigitalInOut(board.SD_CS)
        self._sdcard = None
        try:
            self._sdcard = adafruit_sdcard.SDCard(spi, sd_cs)
            vfs = storage.VfsFat(self._sdcard)
            storage.mount(vfs, "/sd")
        except OSError as error:
            print("No SD card found:", error)

        self._qr_group = None
        # Tracks whether we've hidden the background when we showed the QR code.
        self._qr_only = False

        if self._debug:
            print("Init caption")
        self._caption = None
        if caption_font:
            self._caption_font = bitmap_font.load_font(caption_font)
        self.set_caption(caption_text, caption_position, caption_color)

        if text_font:
            if isinstance(text_position[0], (list, tuple)):
                num = len(text_position)
                if not text_wrap:
                    text_wrap = [0] * num
                if not text_maxlen:
                    text_maxlen = [0] * num
                if not text_transform:
                    text_transform = [None] * num
            else:
                num = 1
                text_position = (text_position, )
                text_color = (text_color, )
                text_wrap = (text_wrap, )
                text_maxlen = (text_maxlen, )
                text_transform = (text_transform, )
            self._text = [None] * num
            self._text_color = [None] * num
            self._text_position = [None] * num
            self._text_wrap = [None] * num
            self._text_maxlen = [None] * num
            self._text_transform = [None] * num
            self._text_font = bitmap_font.load_font(text_font)
            if self._debug:
                print("Loading font glyphs")
            # self._text_font.load_glyphs(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
            #                             b'0123456789:/-_,. ')
            gc.collect()

            for i in range(num):
                if self._debug:
                    print("Init text area", i)
                self._text[i] = None
                self._text_color[i] = text_color[i]
                self._text_position[i] = text_position[i]
                self._text_wrap[i] = text_wrap[i]
                self._text_maxlen[i] = text_maxlen[i]
                self._text_transform[i] = text_transform[i]
        else:
            self._text_font = None
            self._text = None

        # Add any JSON translators
        self._json_transform = []
        if json_transform:
            if callable(json_transform):
                self._json_transform.append(json_transform)
            else:
                self._json_transform.extend(filter(callable, json_transform))

        self._image_json_path = image_json_path
        self._image_url_path = image_url_path
        self._image_resize = image_resize
        self._image_position = image_position
        if image_json_path or image_url_path:
            if self._debug:
                print("Init image path")
            if not self._image_position:
                self._image_position = (0, 0)  # default to top corner
            if not self._image_resize:
                self._image_resize = (320, 240)  # default to full screen
        if hasattr(board, 'TOUCH_XL'):
            if self._debug:
                print("Init touchscreen")
            # pylint: disable=no-member
            self.touchscreen = adafruit_touchscreen.Touchscreen(
                board.TOUCH_XL,
                board.TOUCH_XR,
                board.TOUCH_YD,
                board.TOUCH_YU,
                calibration=((5200, 59000), (5800, 57000)),
                size=(320, 240))
            # pylint: enable=no-member

            self.set_backlight(1.0)  # turn on backlight
        elif hasattr(board, 'BUTTON_CLOCK'):
            if self._debug:
                print("Init cursor")
            self.mouse_cursor = Cursor(board.DISPLAY,
                                       display_group=self.splash,
                                       cursor_speed=8)
            self.mouse_cursor.hide()
            self.cursor = CursorManager(self.mouse_cursor)
        else:
            raise AttributeError(
                'PyPortal module requires either a touchscreen or gamepad.')

        gc.collect()
示例#26
0
文件: snapshot.py 项目: eiselekd/hw
import adafruit_vc0706


# Configuration:
SD_CS_PIN = board.D10  # CS for SD card (SD_CS is for Feather Adalogger)
IMAGE_FILE = '/sd/image.jpg'  # Full path to file name to save captured image.
                              # Will overwrite!

# Setup SPI bus (hardware SPI).
spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)

# Setup SD card and mount it in the filesystem.
sd_cs = digitalio.DigitalInOut(SD_CS_PIN)
sdcard = adafruit_sdcard.SDCard(spi, sd_cs)
vfs = storage.VfsFat(sdcard)
storage.mount(vfs, '/sd')

# Create a serial connection for the VC0706 connection, speed is auto-detected.
uart = busio.UART(board.TX, board.RX, timeout=250)
# Setup VC0706 camera
vc0706 = adafruit_vc0706.VC0706(uart)

# Print the version string from the camera.
print('VC0706 version:')
print(vc0706.version)

# Set the baud rate to 115200 for fastest transfer (its the max speed)
vc0706.baudrate = 115200

# Set the image size.
vc0706.image_size = adafruit_vc0706.IMAGE_SIZE_640x480 # Or set IMAGE_SIZE_320x240 or
示例#27
0
def run_test(pins,
             mosi_pin=MOSI_PIN_NAME,
             miso_pin=MISO_PIN_NAME,
             sck_pin=SCK_PIN_NAME,
             cs_pin=CS_PIN_NAME):

    """
    Performs random writes and reads to file on attached SD card.

    :param list[str] pins: list of pins to run the test on
    :param str mosi_pin: pin name of SPI MOSI
    :param str miso_pin: pin name of SPI MISO
    :param str sck_pin: pin name of SPI SCK
    :param str cs_pin: pin name of SPI CS
    :param str filename: name of file to use as test on SD card
    :return: tuple(str, list[str]): test result followed by list of pins tested
    """

    # Write characters to file on SD card and verify they were written
    if list(set(pins).intersection(set([mosi_pin, miso_pin, sck_pin]))):

        # Tell user to connect SD card
        print("Insert SD card into holder and connect SPI lines to holder.")
        print("Connect " + cs_pin + " to the CS (DAT3) pin on the SD " +
              "card holder.")
        print("WARNING: " + FILENAME + " will be created or overwritten.")
        print("Press enter to continue.")
        input()

        # Configure CS pin
        csel = digitalio.DigitalInOut(getattr(board, cs_pin))
        csel.direction = digitalio.Direction.OUTPUT
        csel.value = True

        # Set up SPI
        spi = busio.SPI(getattr(board, sck_pin),
                        MOSI=getattr(board, mosi_pin),
                        MISO=getattr(board, miso_pin))

        # Try to connect to the card and mount the filesystem
        try:
            sdcard = adafruit_sdcard.SDCard(spi, csel)
            vfs = storage.VfsFat(sdcard)
            storage.mount(vfs, "/sd")
        except OSError:
            print("Could not mount SD card")
            return FAIL, [mosi_pin, miso_pin, sck_pin]

        # Generate test string
        test_str = ""
        for _ in range(NUM_UART_BYTES):
            test_str += chr(random.randint(ASCII_MIN, ASCII_MAX))

        # Write test string to a text file on the card
        try:
            with open("/sd/" + FILENAME, "w") as file:
                print("Writing:\t" + test_str)
                file.write(test_str)
        except OSError:
            print("Could not write to SD card")
            return FAIL, [mosi_pin, miso_pin, sck_pin]

        # Read from test file on the card
        read_str = ""
        try:
            with open("/sd/" + FILENAME, "r") as file:
                lines = file.readlines()
                for line in lines:
                    read_str += line
            print("Read:\t\t" + read_str)
        except OSError:
            print("Could not write to SD card")
            return FAIL, [mosi_pin, miso_pin, sck_pin]

        # Release SPI
        spi.deinit()

        # Compare strings
        if read_str == test_str:
            return PASS, [mosi_pin, miso_pin, sck_pin]

        return FAIL, [mosi_pin, miso_pin, sck_pin]

    # Else (no pins found)
    print("No SD card pins found")
    return NA, []
示例#28
0
import adafruit_sdcard
import supervisor
import json
# See if a card is present
card_detect_pin = digitalio.DigitalInOut(board.SD_CARD_DETECT)
card_detect_pin.direction = digitalio.Direction.INPUT
card_detect_pin.pull = digitalio.Pull.UP
print('SD card present: %s' % card_detect_pin.value)

# Try to connect to the SD card
sdcard = adafruit_sdcard.SDCard(busio.SPI(board.SCK, board.MOSI, board.MISO),
                                digitalio.DigitalInOut(board.SD_CS))

# Mount the card to a directory
virtual_file_system = storage.VfsFat(sdcard)
storage.mount(virtual_file_system, '/sd')
a = {"a": 1, "b": 2}
f = open('/sd/test.yaml', 'w')
json.dump(a, f)
f.close()


def save_settings(values):
    with open('/sd/DAC.txt', 'w') as output_file:
        for i in range(8):
            output_file.write('%f\n' % values[i])


try:
    with open('/sd/DAC.txt', 'r') as input_file:
        values = []
示例#29
0
文件: CS11.py 项目: xinabox/mu-editor
 def __init__(self):
     self.spi = busio.SPI(SCK, MOSI, MISO)
     self.cs = digitalio.DigitalInOut(CS)
     self.sdcard = adafruit_sdcard.SDCard(self.spi, self.cs)
     self.vfs = storage.VfsFat(self.sdcard)
     storage.mount(self.vfs, "/sd")
示例#30
0
    def __init__(self):
        """
        Big init routine as the whole board is brought up.
        """
        self.hardware = {
                       'IMU':    False,
                       'Radio1': False,
                       'Radio2': False,
                       'SDcard': False,
                       'GPS':    False,
                       'MRAM':   False,
                       'WDT':    False,
                       'USB':    False,
                       'PWR':    False,
                       }

        # Define burn wires:
        self._relayA = digitalio.DigitalInOut(board.RELAY_A)
        self._relayA.switch_to_output()
        self._deployA = False

        # Define battery voltage
        self._vbatt = analogio.AnalogIn(board.BATTERY)

        # Define MPPT charge current measurement
        self._ichrg = analogio.AnalogIn(board.L1PROG)

        # Define SPI,I2C,UART
        self.i2c  = busio.I2C(board.SCL,board.SDA)
        self.spi  = busio.SPI(board.SCK,MOSI=board.MOSI,MISO=board.MISO)
        #self.uart = busio.UART(board.TX,board.RX, baudrate=9600, timeout=10)

        # Define GPS
        self.en_gps = digitalio.DigitalInOut(board.EN_GPS)
        self.en_gps.switch_to_output()

        # Define sdcard
        self._sdcs = digitalio.DigitalInOut(board.xSDCS)
        self._sdcs.switch_to_output(value=True)

        # Define radio
        self._rf_cs1 = digitalio.DigitalInOut(board.RF1_CS)
        self._rf_rst1 = digitalio.DigitalInOut(board.RF1_RST)
        self._rf_cs1.switch_to_output(value=True)
        self._rf_rst1.switch_to_output(value=True)
        self._rf_cs2 = digitalio.DigitalInOut(board.RF2_CS)
        self._rf_rst2 = digitalio.DigitalInOut(board.RF2_RST)
        self._rf_cs2.switch_to_output(value=True)
        self._rf_rst2.switch_to_output(value=True)

        # Define MRAM (manual-mode)
        # self._mram_cs = digitalio.DigitalInOut(microcontroller.pin.PB11)
        # self._mram_cs.switch_to_output(value=True)

        # Initialize Neopixel
        try:
            self.neopixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2, pixel_order=neopixel.GRB)
            self.neopixel[0] = (0,0,0)
            self.hardware['Neopixel'] = True
        except Exception as e:
            print('[WARNING][Neopixel]',e)

        # Initialize USB charger
        try:
            self.usb = bq25883.BQ25883(self.i2c)
            self.usb.charging = False
            self.usb.wdt = False
            self.usb.led=False
            self.hardware['USB'] = True
        except Exception as e:
            print('[ERROR][USB Charger]',e)

        # Initialize sdcard
        try:
            self._sd   = adafruit_sdcard.SDCard(self.spi, self._sdcs)
            self._vfs = storage.VfsFat(self._sd)
            storage.mount(self._vfs, "/sd")
            sys.path.append("/sd")
            self.hardware['SDcard'] = True
        except Exception as e:
            print('[ERROR][SD Card]',e)

        # Initialize Power Monitor
        try:
            self.pwr = adm1176.ADM1176(self.i2c)
            self.pwr.sense_resistor = 1
            self.hardware['PWR'] = True
        except Exception as e:
            print('[ERROR][Power Monitor]',e)

        # Initialize IMU
        try:
            self.IMU = bmx160.BMX160_I2C(self.i2c)
            self.hardware['IMU'] = True
        except Exception as e:
            print('[ERROR]',e)

        # Initialize radio(s)
        try:
            self.radio1 = adafruit_rfm9x.RFM9x(self.spi, self._rf_cs1, self._rf_rst1, 433.0)
            self.hardware['Radio1'] = True
        except Exception as e:
            print('[ERROR][RADIO 1]',e)
        try:
            self.radio2 = adafruit_rfm9x.RFM9x(self.spi, self._rf_cs2, self._rf_rst2, 433.0)
            self.hardware['Radio2'] = True
        except Exception as e:
            print('[ERROR][RADIO 2]',e)
示例#31
0
import digitalio
import storage
import adafruit_pcf8523
import _bleio
import adafruit_ble
from adafruit_ble.advertising.standard import Advertisement
from adafruit_ble.services.standard.device_info import DeviceInfoService
from adafruit_ble_berrymed_pulse_oximeter import BerryMedPulseOximeterService

# Logging setup
SD_CS = board.D10
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
cs = digitalio.DigitalInOut(SD_CS)
sd_card = adafruit_sdcard.SDCard(spi, cs)
vfs = storage.VfsFat(sd_card)
storage.mount(vfs, "/sd_card")

log_interval = 2  # you can adjust this to log at a different rate

# RTC setup
I2C = busio.I2C(board.SCL, board.SDA)
rtc = adafruit_pcf8523.PCF8523(I2C)

days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
        "Saturday")

set_time = False
if set_time:  # change to True if you want to write the time!
    #             year, mon, date, hour, min, sec, wday, yday, isdst
    t = time.struct_time((2020, 4, 21, 18, 13, 0, 2, -1, -1))
    # you must set year, mon, date, hour, min, sec and weekday
示例#32
0
cs = digitalio.DigitalInOut(board.D5)
reset = digitalio.DigitalInOut(board.D7)

rfm9x = adafruit_rfm9x.RFM9x(lora_spi, cs, reset, 915.0)

# SD card

#SD_CS = DigitalInOut(board.A5)

# Connect to the card and mount the filesystem.
#spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
sd_cs = digitalio.DigitalInOut(board.A5)
sdcard = adafruit_sdcard.SDCard(lora_spi, sd_cs)
vfs = storage.VfsFat(sdcard)
storage.mount(vfs, "/sd")

# bme280
i2c = busio.I2C(board.SCL, board.SDA)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)

# change this to match the location's pressure (hPa) at sea level
bme280.sea_level_pressure = 1013.25

# display

#display = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c, addr=0x3c, reset=reset_pin)
display = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c, addr=0x3c)

display.fill(0)
display.show()
示例#33
0
def mount_eeprom(eeprom, path, readonly=False):
    eepromvfs = EEPROMVFS(eeprom)
    fs = storage.VfsFat(eepromvfs)
    storage.mount(fs, path, readonly=readonly)
    return fs