Skip to content

Commit c9d76f0

Browse files
authored
Merge pull request adafruit#1082 from jepler/circuitpython-rgbmatrix-1
CircuitPython_RGBMatrix: Add additional example, comment them
2 parents 2aff72d + c57c547 commit c9d76f0

File tree

4 files changed

+204
-33
lines changed

4 files changed

+204
-33
lines changed

CircuitPython_RGBMatrix/fruit.py

Lines changed: 58 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,28 @@
1515
clock_pin=board.D13, latch_pin=board.D0, output_enable_pin=board.D1)
1616
display = framebufferio.FramebufferDisplay(matrix, auto_refresh=False)
1717

18+
# This bitmap contains the emoji we're going to use. It is assumed
19+
# to contain 20 icons, each 20x24 pixels. This fits nicely on the 64x32
20+
# RGB matrix display.
1821
bitmap_file = open("emoji.bmp", 'rb')
1922
bitmap = displayio.OnDiskBitmap(bitmap_file)
2023

24+
# Each wheel can be in one of three states:
2125
STOPPED, RUNNING, BRAKING = range(3)
2226

27+
# Return a duplicate of the input list in a random (shuffled) order.
2328
def shuffled(seq):
2429
return sorted(seq, key=lambda _: random.random())
2530

26-
class Strip(displayio.TileGrid):
31+
# The Wheel class manages the state of one wheel. "pos" is a position in
32+
# scaled integer coordinates, with one revolution being 7680 positions
33+
# and 1 pixel being 16 positions. The wheel also has a velocity (in positions
34+
# per tick) and a state (one of the above constants)
35+
class Wheel(displayio.TileGrid):
2736
def __init__(self):
37+
# Portions of up to 3 tiles are visible.
2838
super().__init__(bitmap=bitmap, pixel_shader=displayio.ColorConverter(),
29-
width=1, height=4, tile_width=20, tile_height=24)
39+
width=1, height=3, tile_width=20)
3040
self.order = shuffled(range(20))
3141
self.state = STOPPED
3242
self.pos = 0
@@ -36,62 +46,91 @@ def __init__(self):
3646
self.stop_time = time.monotonic_ns()
3747

3848
def step(self):
49+
# Update each wheel for one time step
3950
if self.state == RUNNING:
51+
# Slowly lose speed when running, but go at least speed 64
4052
self.vel = max(self.vel * 9 // 10, 64)
4153
if time.monotonic_ns() > self.stop_time:
4254
self.state = BRAKING
4355
elif self.state == BRAKING:
56+
# More quickly lose speed when baking, down to speed 7
4457
self.vel = max(self.vel * 85 // 100, 7)
58+
59+
# Advance the wheel according to the velocity, and wrap it around
60+
# after 7680 positions
4561
self.pos = (self.pos + self.vel) % 7680
62+
63+
# Compute the rounded Y coordinate
4664
yy = round(self.pos / 16)
65+
# Compute the offset of the tile (tiles are 24 pixels tall)
4766
yyy = yy % 24
67+
# Find out which tile is the top tile
4868
off = yy // 24
69+
70+
# If we're braking and a tile is close to midscreen,
71+
# then stop and make sure that tile is exactly centered
4972
if self.state == BRAKING and self.vel == 7 and yyy < 4:
5073
self.pos = off * 24 * 16
5174
self.vel = 0
5275
yy = 0
5376
self.state = STOPPED
54-
self.y = yy % 24 - 20
55-
for i in range(4):
77+
78+
# Move the displayed tiles to the correct height and make sure the
79+
# correct tiles are displayed.
80+
self.y = yyy - 20
81+
for i in range(3):
5682
self[i] = self.order[(19 - i + off) % 20]
5783

84+
# Set the wheel running again, using a slight bit of randomness.
85+
# The 'i' value makes sure the first wheel brakes first, the second
86+
# brakes second, and the third brakes third.
5887
def kick(self, i):
5988
self.state = RUNNING
6089
self.vel = random.randint(256, 320)
6190
self.stop_time = time.monotonic_ns() + 3000000000 + i * 350000000
6291

63-
def brake(self):
64-
self.state = BRAKING
65-
92+
# Our fruit machine has 3 wheels, let's create them with a correct horizontal
93+
# (x) offset and arbitrary vertical (y) offset.
6694
g = displayio.Group(max_size=3)
67-
strips = []
95+
wheels = []
6896
for idx in range(3):
69-
strip = Strip()
70-
strip.x = idx * 22
71-
strip.y = -20
72-
g.append(strip)
73-
strips.append(strip)
97+
wheel = Wheel()
98+
wheel.x = idx * 22
99+
wheel.y = -20
100+
g.append(wheel)
101+
wheels.append(wheel)
74102
display.show(g)
75103

104+
# Make a unique order of the emoji on each wheel
76105
orders = [shuffled(range(20)), shuffled(range(20)), shuffled(range(20))]
77106

78-
for si, oi in zip(strips, orders):
79-
for idx in range(4):
107+
# And put up some images to start with
108+
for si, oi in zip(wheels, orders):
109+
for idx in range(3):
80110
si[idx] = oi[idx]
81111

112+
# We want a way to check if all the wheels are stopped
82113
def all_stopped():
83-
return all(si.state == STOPPED for si in strips)
114+
return all(si.state == STOPPED for si in wheels)
84115

85-
for idx, si in enumerate(strips):
116+
# To start with, though, they're all in motion
117+
for idx, si in enumerate(wheels):
86118
si.kick(idx)
87119

120+
# Here's the main loop
88121
while True:
122+
# Refresh the dislpay (doing this manually ensures the wheels move
123+
# together, not at different times)
89124
display.refresh(minimum_frames_per_second=0)
90125
if all_stopped():
126+
# Once everything comes to a stop, wait a little bit and then
127+
# start everything over again. Maybe you want to check if the
128+
# combination is a "winner" and add a light show or something.
91129
for idx in range(100):
92130
display.refresh(minimum_frames_per_second=0)
93-
for idx, si in enumerate(strips):
131+
for idx, si in enumerate(wheels):
94132
si.kick(idx)
95133

96-
for idx, si in enumerate(strips):
134+
# Otherwise, let the wheels keep spinning...
135+
for idx, si in enumerate(wheels):
97136
si.step()

CircuitPython_RGBMatrix/life.py

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,24 @@
88

99
displayio.release_displays()
1010

11+
# Conway's "Game of Life" is played on a grid with simple rules, based
12+
# on the number of filled neighbors each cell has and whether the cell itself
13+
# is filled.
14+
# * If the cell is filled, and 2 or 3 neighbors are filled, the cell stays
15+
# filled
16+
# * If the cell is empty, and exactly 3 neighbors are filled, a new cell
17+
# becomes filled
18+
# * Otherwise, the cell becomes or remains empty
19+
#
20+
# The complicated way that the "m1" (minus 1) and "p1" (plus one) offsets are
21+
# calculated is due to the way the grid "wraps around", with the left and right
22+
# sides being connected, as well as the top and bottom sides being connected.
23+
#
24+
# This function has been somewhat optimized, so that when it indexes the bitmap
25+
# a single number [x + width * y] is used instead of indexing with [x, y].
26+
# This makes the animation run faster with some loss of clarity. More
27+
# optimizations are probably possible.
28+
1129
def apply_life_rule(old, new):
1230
width = old.width
1331
height = old.height
@@ -25,31 +43,36 @@ def apply_life_rule(old, new):
2543
new[x+yyy] = neighbors == 3 or (neighbors == 2 and old[x+yyy])
2644
xm1 = x
2745

28-
def randomize(output, fraction=0.50):
46+
# Fill 'fraction' out of all the cells.
47+
def randomize(output, fraction=0.33):
2948
for i in range(output.height * output.width):
3049
output[i] = random.random() < fraction
3150

32-
# after xkcd's tribute to John Conway (1937-2020) https://xkcd.com/2293/
33-
conway_data = [
34-
b' +++ ',
35-
b' + + ',
36-
b' + + ',
37-
b' + ',
38-
b'+ +++ ',
39-
b' + + + ',
40-
b' + + ',
41-
b' + + ',
42-
b' + + ',
43-
]
4451

52+
# Fill the grid with a tribute to John Conway
4553
def conway(output):
54+
# based on xkcd's tribute to John Conway (1937-2020) https://xkcd.com/2293/
55+
conway_data = [
56+
b' +++ ',
57+
b' + + ',
58+
b' + + ',
59+
b' + ',
60+
b'+ +++ ',
61+
b' + + + ',
62+
b' + + ',
63+
b' + + ',
64+
b' + + ',
65+
]
4666
for i in range(output.height * output.width):
4767
output[i] = 0
4868
for i, si in enumerate(conway_data):
4969
y = output.height - len(conway_data) - 2 + i
5070
for j, cj in enumerate(si):
5171
output[(output.width - 8)//2 + j, y] = cj & 1
5272

73+
# bit_depth=1 is used here because we only use primary colors, and it makes
74+
# the animation run a bit faster because RGBMatrix isn't taking over the CPU
75+
# as often.
5376
matrix = rgbmatrix.RGBMatrix(
5477
width=64, height=32, bit_depth=1,
5578
rgb_pins=[board.D6, board.D5, board.D9, board.D11, board.D10, board.D12],
@@ -68,21 +91,28 @@ def conway(output):
6891
g2 = displayio.Group(max_size=3, scale=SCALE)
6992
g2.append(tg2)
7093

94+
# First time, show the Conway tribute
7195
palette[1] = 0xffffff
7296
conway(b1)
7397
display.auto_refresh = True
7498
time.sleep(3)
7599
n = 40
76100

77101
while True:
102+
# run 2*n generations.
103+
# For the Conway tribute on 64x32, 80 frames is appropriate. For random
104+
# values, 400 frames seems like a good number. Working in this way, with
105+
# two bitmaps, reduces copying data and makes the animation a bit faster
78106
for _ in range(n):
79107
display.show(g1)
80108
apply_life_rule(b1, b2)
81109
display.show(g2)
82110
apply_life_rule(b2, b1)
83111

112+
# After 2*n generations, fill the board with random values and
113+
# start over with a new color.
84114
randomize(b1)
85-
palette[0] = 0
115+
# Pick a random color out of 6 primary colors or white.
86116
palette[1] = (
87117
(0x0000ff if random.random() > .33 else 0) |
88118
(0x00ff00 if random.random() > .33 else 0) |

CircuitPython_RGBMatrix/scroller.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1+
# This example implements a rainbow colored scroller, in which each letter
2+
# has a different color. This is not possible with
3+
# Adafruit_Circuitpython_Display_Text, where each letter in a label has the
4+
# same color
5+
#
6+
# This demo also supports only ASCII characters and the built-in font.
7+
# See the simple_scroller example for one that supports alternative fonts
8+
# and characters, but only has a single color per label.
9+
110
import array
211

312
from _pixelbuf import wheel
@@ -15,13 +24,18 @@
1524
clock_pin=board.D13, latch_pin=board.D0, output_enable_pin=board.D1)
1625
display = framebufferio.FramebufferDisplay(matrix, auto_refresh=False)
1726

27+
# Create a tilegrid with a bunch of common settings
1828
def tilegrid(palette):
1929
return displayio.TileGrid(
2030
bitmap=terminalio.FONT.bitmap, pixel_shader=palette,
2131
width=1, height=1, tile_width=6, tile_height=14, default_tile=32)
2232

2333
g = displayio.Group(max_size=2)
34+
35+
# We only use the built in font which we treat as being 7x14 pixels
2436
linelen = (64//7)+2
37+
38+
# prepare the main groups
2539
l1 = displayio.Group(max_size=linelen)
2640
l2 = displayio.Group(max_size=linelen)
2741
g.append(l1)
@@ -31,24 +45,29 @@ def tilegrid(palette):
3145
l1.y = 1
3246
l2.y = 16
3347

48+
# Prepare the palettes and the individual characters' tiles
3449
sh = [displayio.Palette(2) for _ in range(linelen)]
3550
tg1 = [tilegrid(shi) for shi in sh]
3651
tg2 = [tilegrid(shi) for shi in sh]
3752

53+
# Prepare a fast map from byte values to
3854
charmap = array.array('b', [terminalio.FONT.get_glyph(32).tile_index]) * 256
3955
for ch in range(256):
4056
glyph = terminalio.FONT.get_glyph(ch)
4157
if glyph is not None:
4258
charmap[ch] = glyph.tile_index
4359

60+
# Set the X coordinates of each character in label 1, and add it to its group
4461
for idx, gi in enumerate(tg1):
4562
gi.x = 7 * idx
4663
l1.append(gi)
4764

65+
# Set the X coordinates of each character in label 2, and add it to its group
4866
for idx, gi in enumerate(tg2):
4967
gi.x = 7 * idx
5068
l2.append(gi)
5169

70+
# These pairs of lines should be the same length
5271
lines = [
5372
b"This scroller is brought to you by CircuitPython & PROTOMATTER",
5473
b" .... . .-.. .-.. --- / .--. .-. --- - --- -- .- - - . .-.",
@@ -61,22 +80,30 @@ def tilegrid(palette):
6180
even_lines = lines[0::2]
6281
odd_lines = lines[1::2]
6382

83+
# Scroll a top text and a bottom text
6484
def scroll(t, b):
85+
# Add spaces to the start and end of each label so that it goes from
86+
# the far right all the way off the left
6587
sp = b' ' * linelen
6688
t = sp + t + sp
6789
b = sp + b + sp
6890
maxlen = max(len(t), len(b))
91+
# For each whole character position...
6992
for i in range(maxlen-linelen):
93+
# Set the letter displayed at each position, and its color
7094
for j in range(linelen):
7195
sh[j][1] = wheel(3 * (2*i+j))
7296
tg1[j][0] = charmap[t[i+j]]
7397
tg2[j][0] = charmap[b[i+j]]
98+
# And then for each pixel position, move the two labels
99+
# and then refresh the display.
74100
for j in range(7):
75101
l1.x = -j
76102
l2.x = -j
77103
display.refresh(minimum_frames_per_second=0)
78104
#display.refresh(minimum_frames_per_second=0)
79105

106+
# Repeatedly scroll all the pairs of lines
80107
while True:
81108
for e, o in zip(even_lines, odd_lines):
82109
scroll(e, o)

0 commit comments

Comments
 (0)