# set to your local the tide predition STATION from the NOAA tide prediction site STATION = "8441241" # Set up a placeholder for DATA_SOURCE that we will update later on DATA_SOURCE = " " DATA_LOCATION = [] # Initialize the pyportal object and set the tides background pyportal = PyPortal(url=DATA_SOURCE, json_path=DATA_LOCATION, status_neopixel=board.NEOPIXEL, default_bg=cwd + "/tides.bmp") pyportal.preload_font() big_font = bitmap_font.load_font(cwd + "/fonts/Arial-Bold-24-Complete.bdf") little_font = bitmap_font.load_font(cwd + "/fonts/Arial-Bold-12.bdf") pyportal.preload_font( b'0123456789fallingrising') # pre-load glyphs for fast printing directionp = (100, 195) high1p = (25, 25) low1p = (25, 85) high2p = (210, 25) low2p = (210, 85) high1t = (25, 50) low1t = (25, 110) high2t = (210, 50) low2t = (210, 110) currentp = (120, 165) timedisp = (120, 225)
graph.draw_line(x1, y1, x2, y2, PROFILE_SIZE, PROFILE_COLOR, 1) # print(point) x1 = x2 y1 = y2 def format_time(seconds): minutes = seconds // 60 seconds = int(seconds) % 60 return "{:02d}:{:02d}".format(minutes, seconds, width=2) timediff = 0 oven = ReflowOvenControl(board.D4) print("melting point: ", oven.sprofile["melting_point"]) font1 = bitmap_font.load_font("/fonts/OpenSans-9.bdf") font2 = bitmap_font.load_font("/fonts/OpenSans-12.bdf") font3 = bitmap_font.load_font("/fonts/OpenSans-16.bdf") label_reflow = label.Label(font1, text="", color=0xFFFFFF, line_spacing=0) label_reflow.x = 0 label_reflow.y = -20 display_group.append(label_reflow) title_label = label.Label(font3, text=TITLE) title_label.x = 5 title_label.y = 14 display_group.append(title_label) # version_label = label.Label(font1, text=VERSION, color=0xAAAAAA) # version_label.x = 300
# Connect to the internet and get local time pyportal.get_local_time() # Setup palette used for plot palette = displayio.Palette(3) palette[0] = 0x0 palette[1] = PLOT_COLOR palette[2] = MARK_COLOR palette.make_transparent(0) # Setup tide plot bitmap tide_plot = displayio.Bitmap(WIDTH, HEIGHT, 3) pyportal.splash.append(displayio.TileGrid(tide_plot, pixel_shader=palette)) # Setup font used for date and time date_font = bitmap_font.load_font(cwd + "/fonts/mono-bold-8.bdf") date_font.load_glyphs(b'1234567890-') # Setup date label date_label = Label(date_font, text="0000-00-00", color=DATE_COLOR, x=7, y=14) pyportal.splash.append(date_label) # Setup time label time_label = Label(date_font, text="00:00:00", color=TIME_COLOR, x=234, y=14) pyportal.splash.append(time_label) # Setup current time marker time_marker_bitmap = displayio.Bitmap(MARK_SIZE, MARK_SIZE, 3) for pixel in range(MARK_SIZE * MARK_SIZE): time_marker_bitmap[pixel] = 2 time_marker = displayio.TileGrid(time_marker_bitmap,
rising_sprite = displayio.TileGrid(rising_bmp, pixel_shader=displayio.ColorConverter()) clue_display.append(rising_sprite) # draw the sinking image sinking_file = open("sinking.bmp", "rb") sinking_bmp = displayio.OnDiskBitmap(sinking_file) sinking_sprite = displayio.TileGrid(sinking_bmp, pixel_shader=displayio.ColorConverter()) clue_display.append(sinking_sprite) # Create text # first create the group text_group = displayio.Group(max_size=5, scale=1) # Make a label reading_font = bitmap_font.load_font("/font/RacingSansOne-Regular-29.bdf") reading_font.load_glyphs( "0123456789ADSWabcdefghijklmnopqrstuvwxyz:!".encode('utf-8')) reading_label = label.Label(reading_font, color=0xffffff, max_glyphs=15) reading_label.x = 10 reading_label.y = 24 text_group.append(reading_label) reading2_label = label.Label(reading_font, color=0xdaf5f4, max_glyphs=15) reading2_label.x = 10 reading2_label.y = 54 text_group.append(reading2_label) reading3_label = label.Label(reading_font, color=0x4f3ab1, max_glyphs=15) reading3_label.x = 10 reading3_label.y = 84
from adafruit_display_text import label import time import rtc from adafruit_bitmap_font import bitmap_font import json import os # Year, Month, doM Hour, Mins, Secs, doY, isDST? current_time = (2020, 3, 6, 4, 45, 9, 3, -1, 0) BLUE = 0x0000FF RED = 0xFF0000 R2 = 0xFF8888 BLUE = 0x00FF00 PURPLE = 0xFF00FF Y_OFFSET = 120 # kourier = bitmap_font.load_font("/kourier.bdf") helv = bitmap_font.load_font("/Helvetica-Bold-16.bdf") current_time = None if "config.json" in os.listdir("/"): with open("/config.json", "r") as f: config = json.load(f) if "time" in config: current_time = tuple(config['time']) clock = rtc.RTC() clock.datetime = current_time def main(): display = board.DISPLAY
def __init__(self, *, url=None, headers=None, json_path=None, regexp_path=None, convert_image=True, default_bg=0x000000, status_neopixel=None, text_font=terminalio.FONT, text_position=None, text_color=0x808080, text_wrap=False, text_maxlen=0, text_transform=None, text_scale=1, json_transform=None, image_json_path=None, image_resize=None, image_position=None, image_dim_json_path=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 self._convert_image = convert_image 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) try: board.DISPLAY.refresh(target_frames_per_second=60) except AttributeError: 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 = 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) 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 text_position is not None and 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 if not isinstance(text_scale, (list, tuple)): text_scale = [text_scale] * num else: num = 1 text_position = (text_position, ) text_color = (text_color, ) text_wrap = (text_wrap, ) text_maxlen = (text_maxlen, ) text_transform = (text_transform, ) text_scale = (text_scale, ) 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_scale = [None] * num if text_font is not terminalio.FONT: self._text_font = bitmap_font.load_font(text_font) else: self._text_font = terminalio.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] if not isinstance(text_scale[i], (int, float)) or text_scale[i] < 1: text_scale[i] = 1 self._text_scale[i] = text_scale[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 self._image_dim_json_path = image_dim_json_path 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 = ( board.DISPLAY.width, board.DISPLAY.height, ) # 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=(board.DISPLAY.width, board.DISPLAY.height), ) # 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()
DATA_LOCATION = [["number"], ["people"]] # determine the current working directory # needed so we know where to find files cwd = __file__.rsplit('/', 1)[0] # Initialize the pyportal object and let us know what data to fetch and where # to display it pyportal = PyPortal(url=DATA_SOURCE, json_path=DATA_LOCATION, status_neopixel=board.NEOPIXEL, default_bg=cwd + "/astronauts_background.bmp", text_font=cwd + "/fonts/Helvetica-Bold-100.bdf", text_position=((180, 0), None), text_color=(0xFFFFFF, None)) names_font = bitmap_font.load_font(cwd + "/fonts/Helvetica-Bold-16.bdf") # pre-load glyphs for fast printing names_font.load_glyphs( b'abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ- ()') names_position = (100, 130) names_color = 0xFF00FF while True: try: value = pyportal.fetch() print("Response is", value) except RuntimeError as e: print("Some error occured, retrying! -", e) stamp = time.monotonic() while (time.monotonic() -
time.sleep(15) # ONE-TIME INITIALIZATION -------------------------------------------------- MATRIX = Matrix(bit_depth=BITPLANES) DISPLAY = MATRIX.display ACCEL = adafruit_lis3dh.LIS3DH_I2C(busio.I2C(board.SCL, board.SDA), address=0x19) _ = ACCEL.acceleration # Dummy reading to blow out any startup residue time.sleep(0.1) DISPLAY.rotation = (int( ((math.atan2(-ACCEL.acceleration.y, -ACCEL.acceleration.x) + math.pi) / (math.pi * 2) + 0.875) * 4) % 4) * 90 LARGE_FONT = bitmap_font.load_font('/fonts/helvB12.bdf') SMALL_FONT = bitmap_font.load_font('/fonts/helvR10.bdf') SYMBOL_FONT = bitmap_font.load_font('/fonts/6x10.bdf') LARGE_FONT.load_glyphs('0123456789:') SMALL_FONT.load_glyphs('0123456789:/.%') SYMBOL_FONT.load_glyphs('\u21A5\u21A7') # Display group is set up once, then we just shuffle items around later. # Order of creation here determines their stacking order. GROUP = displayio.Group(max_size=10) # Element 0 is a stand-in item, later replaced with the moon phase bitmap # pylint: disable=bare-except try: FILENAME = 'moon/splash-' + str(DISPLAY.rotation) + '.bmp' BITMAP = displayio.OnDiskBitmap(open(FILENAME, 'rb')) TILE_GRID = displayio.TileGrid(
mode = 1 # state used to track screen brightness steps_log = 0 # holds total steps to check for steps per hour steps_remaining = 0 # holds the remaining steps needed to reach the step goal sph = 0 # holds steps per hour # variables to hold file locations for background and fonts clue_bgBMP = "/clue_bgBMP.bmp" small_font = "/fonts/Roboto-Medium-16.bdf" med_font = "/fonts/Roboto-Bold-24.bdf" big_font = "/fonts/Roboto-Black-48.bdf" # glyphs for fonts glyphs = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,.: ' # loading bitmap fonts small_font = bitmap_font.load_font(small_font) small_font.load_glyphs(glyphs) med_font = bitmap_font.load_font(med_font) med_font.load_glyphs(glyphs) big_font = bitmap_font.load_font(big_font) big_font.load_glyphs(glyphs) # creating display and default brightness clue_display = board.DISPLAY clue_display.brightness = 0.5 # graphics group clueGroup = displayio.Group() # loading bitmap background # CircuitPython 6 & 7 compatible
board.DISPLAY.brightness = val # Touchscreen setup ts = adafruit_touchscreen.Touchscreen( board.TOUCH_XL, board.TOUCH_XR, board.TOUCH_YD, board.TOUCH_YU, calibration=((5200, 59000), (5800, 57000)), size=(320, 240), ) # ---------- Set the font and preload letters ---------- # Be sure to put your font into a folder named "fonts". font = bitmap_font.load_font("/fonts/Helvetica-Bold-16.bdf") # This will preload the text images. font.load_glyphs( b"abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890- ()") # ------------- User Inretface Eliments ------------- # # Make the display context splash = displayio.Group() board.DISPLAY.show(splash) # Make a background color fill color_bitmap = displayio.Bitmap(320, 240, 1) color_palette = displayio.Palette(1) color_palette[0] = 0x3D0068 bg_sprite = displayio.TileGrid(color_bitmap,
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS: print("ESP32 found and in idle mode") print("Firmware vers.", esp.firmware_version) print("MAC addr:", [hex(i) for i in esp.MAC_address]) print("Connecting to AP...") while not esp.is_connected: try: esp.connect_AP(secrets['ssid'], secrets['password']) except RuntimeError as e: print("could not connect to AP, retrying: ", e) continue # Set the font and preload letters font_large = bitmap_font.load_font("/fonts/Helvetica-Bold-44.bdf") font_small = bitmap_font.load_font("/fonts/Helvetica-Bold-24.bdf") font_large.load_glyphs(b'abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890- ') font_small.load_glyphs(b'abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890- ()') # Set up label for the month label_month = label.Label(font_large, color=LABEL_DAY_COLOR, max_glyphs=200) label_month.x = board.DISPLAY.width // 10 label_month.y = 80 pyportal.splash.append(label_month) # Set up label for the time label_time = label.Label(font_small, color=LABEL_TIME_COLOR, max_glyphs=200) label_time.x = board.DISPLAY.width // 3 label_time.y = 150 pyportal.splash.append(label_time)
#import rtc #rtc.RTC().datetime = time.struct_time((2019, 1, 1, 23, 59, 00, 0, 0, -1)) # determine the current working directory # needed so we know where to find files cwd = ("/" + __file__).rsplit('/', 1)[0] # Initialize the pyportal object and let us know what data to fetch and where # to display it mogwai_image = cwd + "/mogwai_background.bmp" mogwai_sound = cwd + "/mogwai_alarm.wav" gremlin_image = cwd + "/gremlin_background.bmp" gremlin_sound = cwd + "/gremlin_alarm.wav" pyportal = PyPortal(status_neopixel=board.NEOPIXEL, default_bg="pyportal_startup.bmp") big_font = bitmap_font.load_font(cwd + "/fonts/DSEG14ModernMiniBI-44.bdf") big_font.load_glyphs(b'0123456789:AP') # pre-load glyphs for fast printing time_textarea = Label(big_font, max_glyphs=15) time_textarea.x = 0 time_textarea.y = 130 time_textarea.color = 0xFF0000 pyportal.splash.append(time_textarea) # To help us know if we've changed the times, print them out! gremlin_hour, gremlin_min = gremlin_time[3:5] print("Gremlin time: %02d:%02d" % (gremlin_hour, gremlin_min)) mogwai_hour, mogwai_min = mogwai_time[3:5] print("Mogwai time: %02d:%02d" % (mogwai_hour, mogwai_min)) gremlin_since_midnite = gremlin_hour * 60 + gremlin_min mogwai_since_midnite = mogwai_hour * 60 + mogwai_min
from adafruit_bitmap_font import bitmap_font from adafruit_display_shapes.rect import Rect from adafruit_display_text.label import Label from adafruit_button import Button from displayio import Group from terminalio import FONT from collections import namedtuple import board, time from adafruit_pyportal import PyPortal from colors import * from display_setup import display, ts, splash, screen_height, screen_width font = FONT font2 = bitmap_font.load_font("/fonts/Roboto-Medium-16.bdf") glyphs = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,.: ' font2.load_glyphs(glyphs) class TouchKeys: '''Touch keyboard for pyportal usage.''' # Settings BUTTON_WIDTH, BUTTON_HEIGHT = 48, 40 BUTTON_COLOR, BUTTON_TEXT_COLOR = LIGHT_GRAY, BLACK BUTTON_MARGIN, PADDING = 0, 0 MAX_CHARS = 300 LEFT_START, TOP_START = 1, 114 CAPITALIZED = True
import busio from digitalio import DigitalInOut, Direction, Pull import adafruit_pm25 import displayio from adafruit_display_text import label from adafruit_bitmap_font import bitmap_font from adafruit_display_shapes.rect import Rect reset_pin = None # If you have a GPIO, its not a bad idea to connect it to the RESET pin # reset_pin = DigitalInOut(board.G0) # reset_pin.direction = Direction.OUTPUT # reset_pin.value = False # arial12 = bitmap_font.load_font("/fonts/Arial-12.bdf") arial16 = bitmap_font.load_font("/fonts/Arial-16.bdf") # arial24 = bitmap_font.load_font("/fonts/Arial-Bold-24.bdf") display = board.DISPLAY group = displayio.Group(max_size=25) title = label.Label(font=arial16, x=15, y=25, text="PM25 Data", color=0xFFFFFF, max_glyphs=30) group.append(title) level1 = label.Label(font=arial16,
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, 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 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) 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()
type=argparse.FileType('w'), required=True) args = parser.parse_args() class BitmapStub: def __init__(self, width, height, color_depth): self.width = width self.rows = [b''] * height def _load_row(self, y, row): self.rows[y] = bytes(row) f = bitmap_font.load_font(args.font, BitmapStub) # Load extra characters from the sample file. sample_characters = set() if args.sample_file: for line in args.sample_file: # Skip comments because we add additional characters in our huffman comments. if line.startswith("//"): continue for c in line.strip(): sample_characters.add(c) # Merge visible ascii, sample characters and extra characters. visible_ascii = bytes(range(0x20, 0x7f)).decode("utf-8") all_characters = visible_ascii for c in sample_characters:
BUTTON_MARGIN = 20 ########################################################################## # Make a background color fill color_bitmap = displayio.Bitmap(display.width, display.height, 1) color_palette = displayio.Palette(1) color_palette[0] = 0x404040 bg_sprite = displayio.TileGrid(color_bitmap, pixel_shader=color_palette, x=0, y=0) print(bg_sprite.x, bg_sprite.y) splash.append(bg_sprite) ########################################################################## # Load the font font = bitmap_font.load_font(THE_FONT) buttons = [] # Default button styling: button_0 = Button( x=BUTTON_MARGIN, y=BUTTON_MARGIN, width=BUTTON_WIDTH, height=BUTTON_HEIGHT, label="button0", label_font=font, ) buttons.append(button_0) # a button with no indicators at all button_1 = Button(
import board from adafruit_display_text import label from adafruit_bitmap_font import bitmap_font # use built in display (MagTag, PyPortal, PyGamer, PyBadge, CLUE, etc.) # see guide for setting up external displays (TFT / OLED breakouts, RGB matrices, etc.) # https://learn.adafruit.com/circuitpython-display-support-using-displayio/display-and-display-bus display = board.DISPLAY # try uncommenting different font files if you like font_file = "fonts/LeagueSpartan-Bold-16.bdf" # font_file = "fonts/Junction-regular-24.pcf" # Set text, font, and color text = "HELLO WORLD" font = bitmap_font.load_font(font_file) color = 0xFF00FF # Create the tet label text_area = label.Label(font, text=text, color=color) # Set the location text_area.x = 20 text_area.y = 20 # Show it display.show(text_area) while True: pass
# --| USER CONFIG |-------------------------- STATION_ID = ( "9447130" # tide location, find yours here: https://tidesandcurrents.noaa.gov/ ) METRIC = False # set to True for metric units VSCALE = 2 # pixels per ft or m DAILY_UPDATE_HOUR = 3 # 24 hour format # ------------------------------------------- # don't change these PLOT_WIDTH = 116 PLOT_HEIGHT = 116 PLOT_X = 174 PLOT_Y = 6 PLOT_Y_SCALE = round(PLOT_HEIGHT / (4 * VSCALE)) DATE_FONT = bitmap_font.load_font("/fonts/Kanit-Black-24.bdf") TIME_FONT = bitmap_font.load_font("/fonts/Kanit-Medium-20.bdf") # our MagTag magtag = MagTag() magtag.json_path = ["predictions"] # ---------------------------- # Grid overlay for plot # ---------------------------- grid_bmp, grid_pal = adafruit_imageload.load("/bmps/tides_bg_land.bmp") grid_pal.make_transparent(1) grid_overlay = displayio.TileGrid(grid_bmp, pixel_shader=grid_pal) # ---------------------------- # Tide plot (bitmap, palette, tilegrid)
# These pins are used as both analog and digital! XL, XR and YU must be analog # and digital capable. YD just need to be digital ts = adafruit_touchscreen.Touchscreen(board.TOUCH_XL, board.TOUCH_XR, board.TOUCH_YD, board.TOUCH_YU, calibration=((5200, 59000), (5800, 57000)), size=(320, 240)) # Make the display context button_group = displayio.Group(max_size=20) board.DISPLAY.show(button_group) # preload the font print('loading font...') font = bitmap_font.load_font("/fonts/Arial-12.bdf") glyphs = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,.: ' font.load_glyphs(glyphs) # button properties BUTTON_WIDTH = 60 BUTTON_HEIGHT = 60 buttons = [] print('loading colors...') # color conversions (RGB to Philips Hue-compatible HSB) red = my_bridge.rgb_to_hsb([255, 0, 0]) white = my_bridge.rgb_to_hsb([255, 255, 255]) orange = my_bridge.rgb_to_hsb([255, 165, 0]) yellow = my_bridge.rgb_to_hsb([255, 255, 0]) green = my_bridge.rgb_to_hsb([0, 255, 0]) blue = my_bridge.rgb_to_hsb([0, 0, 255])
x=88, y=70 + (event_idx * 40), color=0x000000, text=event_name, line_spacing=0.75, ) pyportal.splash.append(label_event_desc) pyportal.set_background(0xFFFFFF) # Add the header line_header = Line(0, 50, 320, 50, color=0x000000) pyportal.splash.append(line_header) font_h1 = bitmap_font.load_font("fonts/Arial-18.pcf") label_header = label.Label(font_h1, x=10, y=30, color=0x000000) pyportal.splash.append(label_header) # Set up calendar event fonts font_events = bitmap_font.load_font("fonts/Arial-14.pcf") if not google_auth.refresh_access_token(): raise RuntimeError( "Unable to refresh access token - has the token been revoked?") access_token_obtained = int(time.monotonic()) events = [] while True: # check if we need to refresh token if (int(time.monotonic()) - access_token_obtained >=
""" This example uses addfruit_display_text.label to display text using a custom font loaded by adafruit_bitmap_font """ import board from adafruit_display_text import label from adafruit_bitmap_font import bitmap_font display = board.DISPLAY # Set text, font, and color text = "HELLO WORLD" font = bitmap_font.load_font("fonts/Arial-16.bdf") color = 0xFF00FF # Create the tet label text_area = label.Label(font, text=text, color=color) # Set the location text_area.x = 20 text_area.y = 20 # Show it display.show(text_area) while True: pass
bg_palette = displayio.Palette(1) bg_palette[0] = BACKGROUND bg_palette.make_transparent(0) background = displayio.TileGrid(bg_bitmap, pixel_shader=bg_palette) # Add background to display splash.append(background) print('loading fonts...') # Fonts within /fonts/ folder font = cwd + "/fonts/GothamBlack-50.bdf" font_small = cwd + "/fonts/GothamBlack-25.bdf" # pylint: disable=syntax-error data_glyphs = b'0123456789FC-* ' font = bitmap_font.load_font(font) font.load_glyphs(data_glyphs) font_small = bitmap_font.load_font(font_small) full_glyphs = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,.: ' font_small.load_glyphs(full_glyphs) # Label to display Adafruit IO status label_status = Label(font_small, max_glyphs=20) label_status.x = 305 label_status.y = 10 splash.append(label_status) # Create a label to display the temperature label_temp = Label(font, max_glyphs=4) label_temp.x = 35
This example show the use of the backlight as well as using labels to simulate a terminal using a font on the PyPortal """ import os import time import board import displayio from adafruit_bitmap_font import bitmap_font from adafruit_display_text.label import Label fonts = list( filter(lambda x: x.endswith("bdf") and not x.startswith("."), os.listdir("/"))) fonts = [bitmap_font.load_font(x) for x in fonts] print("fade up") # Fade up the backlight for b in range(100): board.DISPLAY.brightness = b / 100 time.sleep(0.01) # default (0.01) demos = [ "CircuitPython = Code + Community", "accents - üàêùéáçãÍóí", "others - αψ◌" ] splash = displayio.Group(max_size=len(fonts) * len(demos)) board.DISPLAY.show(splash) max_y = 0
def add_text( self, text_position=None, text_font=terminalio.FONT, text_color=0x808080, text_wrap=False, text_maxlen=0, text_transform=None, text_scale=1, scrolling=False, line_spacing=1.25, ): """ Add text labels with settings :param str text_font: The path to your font file for your data text display. :param text_position: The position of your extracted text on the display in an (x, y) tuple. Can be a list of tuples for when there's a list of json_paths, for example. :param text_color: The color of the text, in 0xRRGGBB format. Can be a list of colors for when there's multiple texts. Defaults to ``None``. :param text_wrap: Whether or not to wrap text (for long text data chunks). Defaults to ``False``, no wrapping. :param text_maxlen: The max length of the text for text wrapping. Defaults to 0. :param text_transform: A function that will be called on the text before display :param int text_scale: The factor to scale the default size of the text by :param bool scrolling: If true, text is placed offscreen and the scroll() function is used to scroll text on a pixel-by-pixel basis. Multiple text labels with the scrolling set to True will be cycled through. """ if text_font is terminalio.FONT: self._text_font.append(text_font) else: self._text_font.append(bitmap_font.load_font(text_font)) if not text_wrap: text_wrap = 0 if not text_maxlen: text_maxlen = 0 if not text_transform: text_transform = None if not isinstance(text_scale, (int, float)) or text_scale < 1: text_scale = 1 text_scale = round(text_scale) if scrolling: if text_position is None: # Center text if position not specified text_position = (self.display.width, self.display.height // 2 - 1) else: text_position = (self.display.width, text_position[1]) gc.collect() if self._debug: print("Init text area") self._text.append(None) self._text_color.append(self.html_color_convert(text_color)) self._text_position.append(text_position) self._text_wrap.append(text_wrap) self._text_maxlen.append(text_maxlen) self._text_transform.append(text_transform) self._text_scale.append(text_scale) self._text_scrolling.append(scrolling) self._text_line_spacing.append(line_spacing) if scrolling and self._scrolling_index is None: # Not initialized yet self._scrolling_index = self._get_next_scrollable_text_index()
display = board.DISPLAY # determine the current working directory # needed so we know where to find files cwd = ("/" + __file__).rsplit('/', 1)[0] # Set up where we'll be fetching data from DATA_SOURCE = "https://opentdb.com/api.php?amount=1&type=multiple" Q_LOCATION = ['results', 0, 'question'] WA_LOCATION1 = ['results', 0, 'incorrect_answers', 0] WA_LOCATION2 = ['results', 0, 'incorrect_answers', 1] WA_LOCATION3 = ['results', 0, 'incorrect_answers', 2] CA_LOCATION = ['results', 0, 'correct_answer'] # Text info trivia_font = bitmap_font.load_font("/fonts/Arial-ItalicMT-17.bdf") loading_color = 0x8080FF loading_position = (100, 120) loading_text_area = label.Label(trivia_font, max_glyphs=30, color=loading_color, x=loading_position[0], y=loading_position[1]) q_color = 0x8080FF q_position = (25, 70) q_text_area = label.Label(trivia_font, max_glyphs=120, x=q_position[0], y=q_position[1],
for _ in range(k): j = random.randint(0, len(population) - 1) yield population[j] population[j] = population[-1] population.pop() # Initialize the display, cleaning up after a display from the previous run # if necessary displayio.release_displays() bus = board.SPI() framebuffer = sharpdisplay.SharpMemoryFramebuffer(bus, board.D6, 400, 240) display = framebufferio.FramebufferDisplay(framebuffer, auto_refresh=True) # Load our font font = bitmap_font.load_font("/GothamBlack-54.bdf") # Create a Group for the BLM text blm_group = displayio.Group(max_size=10) display.show(blm_group) # Create a 3 line set of text for BLM blm_font = [None, None, None] for line in range(3): label = adafruit_display_text.label.Label(font, color=0xFFFFFF, max_glyphs=16) label.anchor_point = (0, 0) label.anchored_position = (8, line * 84 + 8) blm_font[line] = label blm_group.append(label)
def __init__(self, celsius=True, usa_date=True): """Creates a Thermometer_GFX object. :param bool celsius: Temperature displayed as F or C :param bool usa_date: Use mon/day/year date-time formatting. """ # root displayio group root_group = displayio.Group(max_size=20) board.DISPLAY.show(root_group) super().__init__(max_size=20) self._celsius = celsius self._usa_date = usa_date # create background icon group self._icon_group = displayio.Group(max_size=1) self.append(self._icon_group) board.DISPLAY.show(self._icon_group) # create text object group self._text_group = displayio.Group(max_size=6) self.append(self._text_group) self._icon_sprite = None self._icon_file = None self._cwd = cwd self.set_icon(self._cwd + "/icons/pyportal_splash.bmp") print('loading fonts...') glyphs = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,.:/ ' self.info_font = bitmap_font.load_font(info_font) self.info_font.load_glyphs(glyphs) self.c_font = bitmap_font.load_font(temperature_font) self.c_font.load_glyphs(glyphs) self.c_font.load_glyphs(('°', )) # extra glyph for temperature font print('setting up labels...') self.title_text = Label(self.info_font, text="PyPortal Thermometer") self.title_text.x = 55 self.title_text.y = 15 self._text_group.append(self.title_text) self.subtitle_text = Label(self.info_font, text="Analog Devices ADT7410") self.subtitle_text.x = 43 self.subtitle_text.y = 35 self._text_group.append(self.subtitle_text) self.temp_text = Label(self.c_font, max_glyphs=8) self.temp_text.x = 25 self.temp_text.y = 110 self._text_group.append(self.temp_text) self.time_text = Label(self.info_font, max_glyphs=40) self.time_text.x = 240 self.time_text.y = 150 self._text_group.append(self.time_text) self.date_text = Label(self.info_font, max_glyphs=40) self.date_text.x = 30 self.date_text.y = 160 self._text_group.append(self.date_text) self.io_status_text = Label(self.info_font, max_glyphs=40) self.io_status_text.x = 100 self.io_status_text.y = 220 self._text_group.append(self.io_status_text) board.DISPLAY.show(self._text_group)
spi = busio.SPI(board.SCL, MOSI=board.SDA) tft_cs = board.RX tft_dc = board.TX tft_backlight = board.A3 display_bus = displayio.FourWire(spi, command=tft_dc, chip_select=tft_cs) display = ST7789(display_bus, width=240, height=240, rowstart=80, backlight_pin=tft_backlight, rotation=180) # Setup the various text labels note_font = bitmap_font.load_font("/monoMMM_5_90.bdf") note_text = label.Label(note_font, text="A", color=0xFFFFFF) note_text.x = 90 note_text.y = 100 oct_font = bitmap_font.load_font("/monoMMM_5_24.bdf") oct_text = label.Label(oct_font, text=" ", color=0x00FFFF) oct_text.x = 180 oct_text.y = 150 freq_font = oct_font freq_text = label.Label(freq_font, text="f = 1234.5", color=0xFFFF00) freq_text.x = 20 freq_text.y = 220 # Add everything to the display group
# Use this Boolean variables to select which font style to use ########## use_builtinfont = False # Set True to use the terminalio.FONT BuiltinFont, fontToUse = terminalio.FONT # Set False to use a BDF loaded font, see "fontFiles" below ########## if not use_builtinfont: # load the fonts print("loading font...") fontList = [] # Load some proportional fonts fontFile = "fonts/LeagueSpartan-Bold-16.bdf" fontToUse = bitmap_font.load_font(fontFile) # Set scaling factor for display text my_scale = 1 # Setup the SPI display if "DISPLAY" in dir(board): # use built in display (PyPortal, PyGamer, PyBadge, CLUE, etc.) # see guide for setting up external displays (TFT / OLED breakouts, RGB matrices, etc.) # https://learn.adafruit.com/circuitpython-display-support-using-displayio/display-and-display-bus display = board.DISPLAY else: # Setup the LCD display with driver # You may need to change this to match the display driver for the chipset # used on your display