Esempio n. 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)
Esempio n. 2
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")
Esempio n. 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)
Esempio n. 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)
Esempio n. 5
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")
Esempio n. 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
Esempio n. 8
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")
Esempio n. 9
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")
Esempio n. 10
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)
Esempio n. 11
0
def initfloppy(label="JEDI", capacity=64):
    data = floppy.ADDON_DATA_64KB if capacity == 64 else floppy.ADDON_DATA_32KB
    addon = initaddon("Floppy", "floppy", data)
    eeprom = floppy.create_eeprom(addon)
    eepromvfs = EEPROMVFS(eeprom)
    print("Formating {}K".format(eeprom.size // 1024))
    storage.VfsFat.mkfs(eepromvfs)
    print("Format complete.")
    print("")
    print("Volume label (11 characters, ENTER for none)? {}".format(label))
    fs = storage.VfsFat(eepromvfs)
    fs.label = label
Esempio n. 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)
Esempio n. 13
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
Esempio n. 14
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
Esempio n. 15
0
 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")
Esempio n. 16
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
Esempio n. 17
0
import storage
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:
Esempio n. 18
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()
Esempio n. 19
0
requests.set_interface(esp)

updateBootProgress("Connecting to WIFI", 2)

connectToWifi()

updateBootProgress("Setting up SD Card", 3)
gc.collect()

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

updateBootProgress("Setting up Touch", 4)

# Init Touch Screen
# pylint: disable=no-member
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
Esempio n. 20
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()
Esempio n. 21
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()
Esempio n. 22
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)
Esempio n. 23
0
import gc

gc.threshold((gc.mem_free() + gc.mem_alloc()) // 4)
from flashbdev import bdev
import storage

try:
    if bdev:
        vfs = storage.VfsFat(bdev)
        storage.mount(vfs, '/')
except OSError:
    import inisetup
    inisetup.setup()

gc.collect()
Esempio n. 24
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, []
Esempio n. 25
0
def mount():
    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, "/sd")
Esempio n. 26
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!')
Esempio n. 27
0
    def __init__(self):
        """
        Big init routine as the whole board is brought up. 
        """
        self.hardware = {
            'IMU': False,
            'radio': False,
            'SDcard': False,
            'GPS': False,
            'MRAM': False,
            'WDT': False,
        }

        # Define LEDs:
        self._led = digitalio.DigitalInOut(board.LED)
        self._led.switch_to_output()

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

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

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

        # Define battery current draw
        self._idraw = analogio.AnalogIn(board.IBATT)

        # 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)

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

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

        # Define radio
        self._rf_cs = digitalio.DigitalInOut(board.RF_CS)
        self._rf_rst = digitalio.DigitalInOut(board.RF_RST)
        self._rf_cs.switch_to_output(value=True)
        self._rf_rst.switch_to_output(value=True)

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

        # 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]', e)

        # Initialize IMU
        try:
            self.IMU = adafruit_lsm9ds1.LSM9DS1_I2C(self._i2c)
            self.hardware['IMU'] = True
        except Exception as e:
            print('[ERROR]', e)

        # Initialize radio
        try:
            self.radio = adafruit_rfm9x.RFM9x(self._spi, self._rf_cs,
                                              self._rf_rst, 433.0)
            self.hardware['Radio'] = True
        except Exception as e:
            print('[ERROR]', e)
Esempio n. 28
0
# SD card usage
import board
import digitalio
import sdcard
import storage

spi = board.SPI()
cs = digitalio.DigitalInOut(board.P7)
sd = sdcard.SDCard(spi, cs)
vfs = storage.VfsFat(sd)
storage.mount(vfs, "/sd")
print("microSD Card mounted.")

# write to sd card
print("Writing to file /sd/test.txt ...")
with open("/sd/test.txt", "w") as f:
    f.write("This is the written string.\n")

# read from sd card
print("Reading from file /sd/test.txt ...")
with open("/sd/test.txt", "r") as f:
    data = f.read()
    print(data)
Esempio n. 29
0
lora_spi = busio.SPI(board.D13, MOSI=board.D11, MISO=board.D12)

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)
Esempio n. 30
0
def mount_eeprom(eeprom, path, readonly=False):
    eepromvfs = EEPROMVFS(eeprom)
    fs = storage.VfsFat(eepromvfs)
    storage.mount(fs, path, readonly=readonly)
    return fs