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 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. 4
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)
Esempio n. 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")

    print("Taking Screenshot...")
    save_pixels("/sd/screenshot.bmp")
    print("Screenshot taken")
Esempio n. 6
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. 7
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. 8
0
import neopixel
import simpleio
import adafruit_sdcard
import microcontroller
import storage
import os

# Set up Objects--------------------------------------------------------------:
led = digitalio.DigitalInOut(board.D13)
led.direction = digitalio.Direction.OUTPUT
pixels = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2, auto_write=True)
uart = busio.UART(board.TX, board.RX, baudrate=9600)
# SD Card Objects
spi = busio.SPI(board.SD_SCK, board.SD_MOSI, board.SD_MISO)
cs = digitalio.DigitalInOut(board.SD_CS)
sdcard = adafruit_sdcard.SDCard(spi, cs)
vfs = storage.VfsFat(sdcard)
storage.mount(vfs, "/sd")

# Colors
RED = (50, 0, 0)
YELLOW = (50, 30, 0)
GREEN = (0, 50, 0)
CYAN = (0, 50, 50)
BLUE = (0, 0, 50)
PURPLE = (40, 0, 50)
WHITE = (50, 50, 50)
BYELLOW = (100, 60, 0)


# Movement routines:--------------------------------------------------------:
Esempio n. 9
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. 10
0
    def __init__(self,
                 measurements,
                 headers=None,
                 filename=None,
                 use_SD=True,
                 spi=None,
                 SD_CS=None):
        """__init__
        :param int measurements: The number of different measurements that will be taken per reading.
        :param list headers: A list of strings of headers for the different measurements. List length must be equal to `measurements`. If None, headers will not be used.
        :param string filename: Filename of the log. Defaults to `log.txt` if none is supplied.
        :param bool use_SD: Whether to write to the SD card or the local filesystem. Defaults to SD.
        :param spi: A supplied spi bus. Creates it's own if none is supplied. Only used if `use_SD` is `True`.
        :param SD_CS: The SD card's chip select pin. if none is supplied, it will try the inbuilt `board.SD_CS`
        """

        self.reading_no = 0
        self.num_measurements = 0

        if headers:
            assert (
                measurements == len(headers)
            ), "The number of headers must equal the number of different measurements"

            self.num_measurements = measurements

            self.headers = ["Reading no"] + headers

        if filename:
            self.filename = filename
        else:
            self.filename = "log.txt"

        import storage

        if use_SD:
            import adafruit_sdcard, digitalio

            if spi:
                self.spi = spi
            else:
                import board
                self.spi = board.SPI()

            if SD_CS:
                self.SD_CS = SD_CS
            else:
                import board
                try:
                    self.SD_CS = board.SD_CS
                except AttributeError:
                    raise AttributeError(
                        "Your board does not have a built in SD card, please supply the chip select pin for the SD card of the addon board"
                    )

            self.sdcard = adafruit_sdcard.SDCard(
                self.spi, digitalio.DigitalInOut(self.SD_CS))
            self.vfs = storage.VfsFat(self.sdcard)
            storage.mount(self.vfs, "/sd")

            self.filepath = "/sd/" + self.filename

        else:
            #print("WARNING!! This will not work unless you have set up boot.py to mount the filesystem as rw, see https://learn.adafruit.com/circuitpython-essentials/circuitpython-storage")

            try:
                storage.remount("/")

                self.filepath = "/" + self.filename
            except RuntimeError as e:
                raise RuntimeError(
                    str(e) +
                    "\nLocal filesystem logging will only work when CIRCUITPY is not mounted by a computer"
                )  # will only work once running a release after https://github.com/adafruit/circuitpython/commit/8e8eb07

        try:
            with open(self.filepath, "r") as f:
                # check if continuing last log or starting a new one
                firstline = f.readline().split(",")
                for index, value in enumerate(firstline):
                    firstline[index] = value.strip()
                if firstline == self.headers or firstline[0] == "0":
                    for line in f:
                        if line != "\n":
                            lastline = line
                    lastline = lastline.split(",")
                    self.reading_no = int(lastline[0]) + 1
                    self.num_measurements = len(lastline) - 1
                    newfileneeded = False
                else:
                    from os import rename
                    rename(self.filepath, self.filepath + ".old")
                    newfileneeded = True

        except OSError as e:
            if e.args[0] == 2:
                # no such file
                newfileneeded = True

            elif e.args[0] == 30:
                # read only fs
                raise RuntimeError(
                    "The filesystem has been mounted as read only")

        if newfileneeded:
            with open(self.filepath, "w") as f:
                if headers:
                    f.write(', '.join(str(x) for x in self.headers))
                    f.write("\n")
Esempio n. 11
0
from adafruit_button import Button
import adafruit_touchscreen
import busio
import digitalio
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])
Esempio n. 12
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. 13
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. 14
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. 15
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. 16
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. 17
0
spi_bus = busio.SPI(board.SCK, board.MOSI, board.MISO)
i2c_bus = busio.I2C(board.SCL, board.SDA)

# Initialize the onboard clock
rtc = adafruit_pcf8523.PCF8523(i2c_bus)
# Set the onboard clock if needed
# The format is (year, month, day, hour, minute, second, dayOfWeek, dayInYear, isDST)
# See https://docs.python.org/3/library/time.html#time.struct_time for more details
# Uncomment the next two lines to set the onboard clock:
# rtc.datetime = time.struct_time(
#     (2020,  6,   24,   14,  40,  0,    0,   -1,    -1))

# SD
SD_CS = board.D10
cs = digitalio.DigitalInOut(SD_CS)
sdcard = adafruit_sdcard.SDCard(spi_bus, cs)
vfs = storage.VfsFat(sdcard)
storage.mount(vfs, "/sd")

# Create metadata file
meta = {}
meta["pilot"] = "Fill this in."
t = rtc.datetime
meta["date-start"] = "%s-%s-%s" % (t.tm_mon, t.tm_mday, t.tm_year)
meta["time-start"] = "%s:%s:%s" % (t.tm_hour, t.tm_min, t.tm_sec)
meta["location"] = "Fill this in."
meta["TimeZone"] = "PST"
with open('/sd/meta.json', 'w') as outfile:
    json.dump(meta, outfile)

# Set the Neopixel to green now that we found a valid SD card
Esempio n. 18
0
import board
import adafruit_sdcard
import sys
import digitalio
import busio
import storage

# Initialize SD card
print("Setting up communication with SDCard...")
sd_spi = busio.SPI(board.SD_SCK, board.SD_MOSI, board.SD_MISO)
sd_cs = digitalio.DigitalInOut(board.SD_CS)
sdcard = adafruit_sdcard.SDCard(sd_spi, sd_cs)

print("Mounting...")
vfs = storage.VfsFat(sdcard)
storage.mount(vfs, "/sd")
sys.path.append("/sd")
Esempio n. 19
0
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import board
import digitalio
import adafruit_sdcard
import storage
from adafruit_pyoa import PYOA_Graphics

try:
    sdcard = adafruit_sdcard.SDCard(board.SPI(),
                                    digitalio.DigitalInOut(board.SD_CS))
    vfs = storage.VfsFat(sdcard)
    storage.mount(vfs, "/sd")
    print("SD card found")  # no biggie
except OSError:
    print("No SD card found")  # no biggie

gfx = PYOA_Graphics()

gfx.load_game("/cyoa")
current_card = 0  # start with first card

while True:
    print("Current card:", current_card)
    current_card = gfx.display_card(current_card)
Esempio n. 20
0
def dir_command():
    sdcard = adafruit_sdcard.SDCard(spi, digitalio.DigitalInOut(sd_cs))
    vfs = storage.VfsFat(sdcard)
    storage.mount(vfs, '/sd')
    return "{}\n\r".format(os.listdir('/sd/'))
Esempio n. 21
0
spi = board.SPI()
i2c = board.I2C()

# 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='')
Esempio n. 22
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. 23
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)
Esempio n. 24
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")