Created
March 15, 2024 17:23
-
-
Save rhammell/df2a1445976148d8e895e40facd1cad2 to your computer and use it in GitHub Desktop.
CircuitPython script to display icons on TFT display
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import random | |
import board | |
import displayio | |
import fourwire | |
import adafruit_ili9341 | |
import pwmio | |
# Create display | |
displayio.release_displays() | |
spi = board.SPI() | |
tft_cs = board.D9 | |
tft_dc = board.D10 | |
display_bus = fourwire.FourWire(spi, command=tft_dc, chip_select=tft_cs, reset=board.D7) | |
display = adafruit_ili9341.ILI9341(display_bus, width=320, height=240) | |
display.auto_refresh = False | |
display.rotation = 270 | |
# Change backlight brightness | |
brightness = 0.1 | |
duty_cycle = int(brightness * 65535) | |
frequency = 500 | |
backlight_pwm = pwmio.PWMOut(board.D5, duty_cycle=duty_cycle, frequency=frequency) | |
# Create main display groups | |
main_group = displayio.Group() | |
display.root_group = main_group | |
# Icon file names | |
icon_fnames = [ | |
'img/snowman.bmp', | |
'img/santa.bmp', | |
'img/glove.bmp', | |
'img/ornament.bmp', | |
'img/present.bmp', | |
'img/tree.bmp', | |
'img/candle.bmp', | |
'img/stocking.bmp', | |
'img/lollipop.bmp', | |
'img/hat.bmp', | |
'img/cup.bmp', | |
'img/candycane.bmp', | |
'img/snowflake.bmp', | |
'img/gingerbread.bmp' | |
] | |
# Define bouncing icon class | |
class BouncingIcon: | |
def __init__(self, fname, x, y, speed_x, speed_y): | |
image = displayio.OnDiskBitmap(fname) | |
image.pixel_shader.make_transparent(0) | |
self.icon = displayio.TileGrid( | |
image, | |
pixel_shader=image.pixel_shader, | |
x=x, | |
y=y | |
) | |
main_group.append(self.icon) | |
self.speed_x = speed_x | |
self.speed_y = speed_y | |
# Init icons array | |
icon_size = 40 | |
icons = [] | |
# Create BouncingIcon instance for each filename | |
for icon_fname in icon_fnames: | |
icons.append(BouncingIcon( | |
icon_fname, | |
random.randint(0, display.width - icon_size), | |
random.randint(0, display.height - icon_size), | |
random.choice([-1, 1]), | |
random.choice([-1, 1]) | |
)) | |
# Miain loop | |
while True: | |
time.sleep(0.01) | |
print('test') | |
for icon in icons: | |
# Update icon position | |
icon.icon.x += icon.speed_x | |
icon.icon.y += icon.speed_y | |
# Bounce off the right and left edges | |
if icon.icon.x + icon_size >= display.width or icon.icon.x <= 0: | |
icon.speed_x = -icon.speed_x | |
# Bounce off the bottom and top edges | |
if icon.icon.y + icon_size >= display.height or icon.icon.y <= 0: | |
icon.speed_y = -icon.speed_y | |
display.refresh() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment