Overview
Each new generation of the Raspberry Pi brings improvements over the last, and the Raspberry Pi 5 is no exception. However, along with the great new features and enhanced performance can also come some incompatibility with the way things were done on prior versions of the hardware. One such incompatibility with the Pi 5 was the ability to drive HUB75 compatible RGB Matrices like the older Pi's could.
The new Adafruit Blinka Raspberry Pi5 PioMatter library brings this capability to the Raspberry Pi 5 by way of the PIO peripherals.
Hardware Requirements
You'll need a Raspberry Pi 5, we recommend the official Raspberry Pi 5V power supply for it. There are a variety of matrix panels and power supplies to choose from depending on how big or small you're project will be.
Each panel requires up to 4A of power at max brightness with all pixels on. Keeping things a bit dimmer, or not using all the pixels at once will save power. I've had success running 2 panels off of one 4A power adapter, the matrices are still plenty bright for indoor projects.
If you're driving more than 2 panels, you'll need another 4A adapter. The female DC power adapter makes it easy to power additional matrices separate from the two that can be powered from the Bonnet's terminal blocks.
The library supports both the RGB Matrix Bonnet, and the RGB Matrix HAT. Only one is needed though, choice is up to you.
Page last edited February 05, 2025
Raspberry Pi 5 Setup
We recommend you use the latest Raspberry Pi OS flashed onto one of the official Raspberry Pi SDCards. The Raspberry Pi Imager app makes it easy to prepare your SD Card.
- Click Choose Device then select the Raspberry Pi 5.
- Click Choose OS then select Raspberry Pi OS (64-bit).
- Click Choose Storage then select your SDCard adapter. The name will depend on your device and it may differ from the screenshot.
Once all 3 values are selected you should see them filled in to the appropriate areas of the main screen.
When everything has been set, click the Next button. You'll be asked if you'd like to apply OS customization settings. This step is optional, it allows you to put in username, WiFi credentials, and SSH public key which will get baked in to the image that is flashed to the SD Card.
Enter your details and click Yes if you'd like to do it, otherwise click No. Next you'll be warned that the storage device you've select is going to be erased. Make certain it's the drive you're intending to flash and then click Yes to start the writing process.
A pop-up will be shown once the writing has completed successfully.
Boot & Update
If you did enter your network credentials and SSH key to the OS customization step, and you can use nmap or some other tool to locate the Pi 5 on the network and then you can do this step entirely "headless". If not you can temporarily plug in an HDMI display and USB keyboard to do it.
Plug in the Pi 5, let it boot up, then update the software on it using the following commands.
sudo rpi-update is needed especially for older Pi 5 boards.
sudo rpi-update sudo apt update sudo apt upgrade sudo apt-get install python3-pip sudo reboot
Create a Virtual Environment
The best practice for installing Python libraries is to use virtual environments to keep things isolated and minimize conflicts between different versions of libraries that might be required for different projects or purposes. You can name your virtual environment anything, but it's best to use something you'll remember and associate with the project your working on. I use the name blinka_venv for the environment containing Adafruit Blinka and all associated libraries on my Pi's.
It's easy to create one with the following command.
python -m venv ~/venvs/blinka_venv
For more info about virtual environments see this guide.
Install Requirements
Next you need to activate the new virtual environment and then install the required libraries within it.
source ~/venvs/blinka_venv/bin/activate pip install adafruit-blinka pip install pillow pip install numpy pip install click pip install Adafruit-Blinka-Raspberry-Pi5-Piomatter
Add PIO Subsystem Rule Configuration
By default one requires root privilege to access the PIO hardware peripherals. We'll setup a rule that makes it so that the standard user can do it. We need to edit the file /etc/udev/rules.d/99-com.rules.
sudo nano /etc/udev/rules.d/99-com.rules
Add a new empty line or two at the top of the file by pressing enter. Then add this to one of the empty lines.
SUBSYSTEM=="*-pio", GROUP="gpio", MODE="0660"
To save the file press Ctrl-S on the keyboard. Then press Ctrl-X to exit. After you've done this, reboot the Pi with sudo reboot
Accessing Console
At present time, the python scripts that drive the matrices work best when run from the console context rather than the desktop UI context. There are a few ways you can achieve this, and depending on whether your Pi is dedicated to this usage or not you may want to set it up to boot directly to the console.
Temporary
If you don't want to make any config changes then you can simply press Ctrl-Alt-F1 on a keyboard connected to the Pi to change from the desktop context to the console. The HDMI screen will go from showing the desktop to just the basic terminal prompt. At this prompt you can activate your virtual environment as shown above, and then run Python scripts that draw to the matrix. To go back to the desktop context you can press Ctrl-Alt-F7.
SSH
If you access the Pi over SSH then it already counts as the console so you can activate your virtual environment and run the matrix scripts with nothing further needed.
Auto Boot to Console
If you intend to keep using the same Pi for RGB Matrix projects, and you typically use a keyboard and HDMI screen to interact with the Pi directly, rather than SSH, then it may be convenient to configure your Pi to automatically boot directly to the console rather than the desktop.
To enter the config utility run this command.
sudo raspi-config
- Ensure System Options is highlighted and press enter.
- Arrow down to highlight Boot / Auto Login and press enter.
- Highlight either B1 Console, or B2 Console Autologin and press enter.
- After the setting is applied you'll be taken back to the main raspi-config screen
- Arrow right until Finish is highlighted and press enter.
- When prompted to reboot now highlight Yes and press enter.
When the Pi boots up you'll be ready to activate your virtual environment and run the python scripts that interact with the RGB Matrix.
Page last edited February 05, 2025
Wiring
The RGB Matrix Bonnet and RGB Matrix HAT make it easy to wire up the RGB Matrix and required power supply.
It is best to make all of these connections with the power unplugged, and then once everything is connected and you've double-checked that it's all correct, plug in the power to turn everything on. I've found that the Pi can complain about low power if its USB C power is not plugged in prior to the DC jack power on the Bonnet or Hat. So be sure to plug in the USB C power adapter first, then the adapters powering the Bonnet and any additional panels.
For more info see this guide page.
Pi 5 & Bonnet Connections
- Attach the Matrix Bonnet or Hat to the Raspberry Pi 5 GPIO pin rows.
- Connect the USB C power cable to the USB C jack to power the Pi.
- Connect the barrel jack of the DC 5V 4A power adapter into the barrel jack connector on the Matrix Bonnet or Hat.
- Connect the fork on the end of GND (black wire) lead on the matrix power cable to the - terminal block on the Matrix Bonnet or Hat.
- Connect the fork on the end of the 5V (red wire) lead on the matrix power cable to the + terminal block on the Matrix Bonnet or Hat.
- Connect one end of a 2x8 IDC ribbon cable to the 2x8 pin connector on the Matrix Bonnet or Hat.
- Connect one end of the 4 pin matrix power cable connector to the 4 pin power input connector on the back of the matrix panel.
- Connect the other end of the 2x8 IDC ribbon cable to the input 2x8 pin connector on the back of the matrix panel. The input connector is the one that the arrows in the long direction point away from.
Page last edited February 05, 2025
Basic Test
Once you're Pi 5 is all set up and you've got the RGB Matrix panels all wired you're ready to test it out!
As always, you need to activate the virtual environment before running the example. If you haven't already then activate it like this.
source ~/venvs/blinka_venv/bin/activate
Next you can run the single_panel_simpletest.py script.
python single_panel_simpletest.py
The code for this example is embedded below. You can download it, or copy/paste the text into a file.
#!/usr/bin/python3
# SPDX-FileCopyrightText: 2025 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
Display a simple test pattern of 3 shapes on a single 64x32 matrix panel.
Run like this:
$ python simpletest.py
"""
import numpy as np
from PIL import Image, ImageDraw
import adafruit_blinka_raspberry_pi5_piomatter as piomatter
width = 64
height = 32
geometry = piomatter.Geometry(width=width, height=height, n_addr_lines=4,
rotation=piomatter.Orientation.Normal)
canvas = Image.new('RGB', (width, height), (0, 0, 0))
draw = ImageDraw.Draw(canvas)
framebuffer = np.asarray(canvas) + 0 # Make a mutable copy
matrix = piomatter.PioMatter(colorspace=piomatter.Colorspace.RGB888Packed,
pinout=piomatter.Pinout.AdafruitMatrixBonnet,
framebuffer=framebuffer,
geometry=geometry)
draw.rectangle((2, 2, 10, 10), fill=0x008800)
draw.circle((18, 6), 4, fill=0x880000)
draw.polygon([(28, 2), (32, 10), (24, 10)], fill=0x000088)
framebuffer[:] = np.asarray(canvas)
matrix.show()
input("Press enter to exit")
Page last edited February 05, 2025
Initialization Config
Initializing matrix panels to display things onto requires 3 main steps:
- Create a Geometry object to define the size and shape of the panel(s)
- Create a framebuffer to hold display data
- Create the PioMatter instance.
Geometry
The Geometry object defines the size and shape of the panel(s) that will serve as the display. There 6 arguments that can be passed to configure it.
-
width- The total width of the panel(s) in pixels. -
height- The total height of the panel(s) in pixels. -
n_addr_lines- The number of connected address lines. The number of pixels in the shift register is automatically computed from these values. Many panels use4as a standard. The 64x64 panels that we stock use5address lines. Set this value according to which panels you're using. Note that using 5 addr lines also requires soldering a jumper as described on this guide page. -
serpentine- Controls the arrangement of multiple panels when they are stacked in rows. If it isTrue, then each row goes in the opposite direction of the previous row. Default isTrue. -
rotation- controls the orientation of the panel(s). Must be one of theOrientationconstants. Default isOrientation.Normal. Over valid values areOrientation.R180,Orientation.CW, andOrientation.CCW -
n_planes- Controls the color depth of the panel. This is separate from the framebuffer layout. Decreasingn_planescan increase FPS at the cost of reduced color fidelity. The default,10, is the maximum value. -
n_temporal_planes- Controls the temporal dithering. Valid values are0,2, and4. Cannot be higher thann_planes. The default is0. Using larger values can increase the framerate in some cases experiment with your panels and application. -
map- A pixel/lanes mapping list. For Active3 configurations usesimple_multilane_mapper(width, height, n_addr_lines, n_lanes). For single matrix bonnet/HAT this can be omitted.
Framebuffer
Next you need a framebuffer, this is a numpy array that will contain pixel data in the appropriate colorspace. When refreshed the matrix will show the data that is in this framebuffer on the display. Depending on what you're displaying it can be created in a few different ways.
# For displaying an image from PIL, canvas is the PIL.Image instance framebuffer = np.asarray(canvas) + 0 # For displaying arbitrary data, start with zeros framebuffer = np.zeros(shape=(geometry.height, geometry.width, 3), dtype=np.uint8)
PioMatter
Now the PioMatter instance can be initialized. Aside from the Geometry, and Framebuffer created above, it also accepts arguments for colorspace and pinout.
-
colorspace- Controls the colorspace that will be used for data to be displayed.
It must be one of theColorspaceconstants. Which to use depends on what data
your displaying and how it is processed before copying into the framebuffer. Many of the examples useColorspace.RGB888Packed. Other valid values areColorspace.RGB565andColorspace.RGB888 -
pinout- Defines which pins the panels are wired to. Different pinouts can support different hardware breakouts and panels with different color order. The value must be one of thePinoutconstantsPinout.AdafruitMatrixBonnet,Pinout.AdafruitMatrixBonnetBGR,Pinout.AdafruitMatrixHat, orPinout.AdafruitMatrixHatBGR. For the active3/Triple Matrix Bonnet usePinout.Active3orPinout.Active3BGR -
framebuffer- Anumpy.arraybuffer as noted above. -
geometry- AGeometryinstance as noted above.
geometry = piomatter.Geometry(width=64, height=32, n_addr_lines=4, rotation=piomatter.Orientation.Normal) matrix_framebuffer = np.zeros(shape=(geometry.height, geometry.width, 3), dtype=np.uint8) matrix = piomatter.PioMatter(colorspace=piomatter.Colorspace.RGB888Packed, pinout=piomatter.Pinout.AdafruitMatrixBonnet, framebuffer=matrix_framebuffer, geometry=geometry)
Triple Matrix Bonnet:
pixelmap = simple_multilane_mapper(width, height, n_addr_lines, n_lanes)
geometry = piomatter.Geometry(width=width, height=height, n_addr_lines=n_addr_lines, n_planes=10, n_temporal_planes=4, map=pixelmap, n_lanes=n_lanes)
framebuffer = np.asarray(canvas) + 0 # Make a mutable copy
matrix = piomatter.PioMatter(colorspace=piomatter.Colorspace.RGB888Packed,
pinout=piomatter.Pinout.Active3,
framebuffer=framebuffer,
geometry=geometry)
Page last edited February 05, 2025
Multiple Matrix Panels
Is one panel too small to contain your epic ideas? No problem, you can chain multiple panels together in a serpentine configuration to assemble a larger total display size. When wiring multiple panels, be sure to pay attention to the arrows on the silkscreen of the back of the matrix panels. The arrows in the long direction point away from the input 2x8 IDC connector and point towards the output 2x8 IDC connector.
Various possible configurations are illustrated below.
Once your panels are properly wired up be sure to update the width and height values used in the code when the matrices are initialized.
Page last edited February 05, 2025
Animated GIF
As always, you need to activate the virtual environment before running the example. If you haven't already then activate it like this.
source ~/venvs/blinka_venv/bin/activate
Next you can run the play_gif.py script.
python play_gif.py
The code for this example is embedded below. You can download it, or copy/paste the text into a file.
#!/usr/bin/python3
"""
Display an animated gif
Run like this:
$ python play_gif.py
The animated gif is played repeatedly until interrupted with ctrl-c.
"""
import time
import numpy as np
import PIL.Image as Image
import adafruit_blinka_raspberry_pi5_piomatter as piomatter
width = 64
height = 32
gif_file = "nyan.gif"
canvas = Image.new('RGB', (width, height), (0, 0, 0))
geometry = piomatter.Geometry(width=width, height=height,
n_addr_lines=4, rotation=piomatter.Orientation.Normal)
framebuffer = np.asarray(canvas) + 0 # Make a mutable copy
matrix = piomatter.PioMatter(colorspace=piomatter.Colorspace.RGB888Packed,
pinout=piomatter.Pinout.AdafruitMatrixBonnet,
framebuffer=framebuffer,
geometry=geometry)
with Image.open(gif_file) as img:
print(f"frames: {img.n_frames}")
while True:
for i in range(img.n_frames):
img.seek(i)
canvas.paste(img, (0,0))
framebuffer[:] = np.asarray(canvas)
matrix.show()
time.sleep(0.1)
Page last edited February 05, 2025
Scrolling Text
As always, you need to activate the virtual environment before running the example. If you haven't already then activate it like this.
source ~/venvs/blinka_venv/bin/activate
Next you can run the quote_scroller.py script.
python quote_scroller.py
The code for this example is embedded below. You can download it, or copy/paste the text into a file.
#!/usr/bin/python3
# SPDX-FileCopyrightText: 2025 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
Display quote from the Adafruit quotes API as text scrolling across the
matrices.
Requires the requests library to be installed.
Run like this:
$ python quote_scroller.py
"""
import numpy as np
import requests
from PIL import Image, ImageDraw, ImageFont
import adafruit_blinka_raspberry_pi5_piomatter as piomatter
# 128px for 2x1 matrices. Change to 64 if you're using a single matrix.
total_width = 128
total_height = 32
bottom_half_shift_compensation = 1
font_color = (0, 128, 128)
# Load the font
font = ImageFont.truetype("LindenHill-webfont.ttf", 26)
quote_resp = requests.get("https://www.adafruit.com/api/quotes.php").json()
text = f'{quote_resp[0]["text"]} - {quote_resp[0]["author"]}'
#text = "Sometimes you just want to use hardcoded strings. - Unknown"
x, y, text_width, text_height = font.getbbox(text)
full_txt_img = Image.new("RGB", (int(text_width) + 6, int(text_height) + 6), (0, 0, 0))
draw = ImageDraw.Draw(full_txt_img)
draw.text((3, 3), text, font=font, fill=font_color)
full_txt_img.save("quote.png")
single_frame_img = Image.new("RGB", (total_width, total_height), (0, 0, 0))
geometry = piomatter.Geometry(width=total_width, height=total_height,
n_addr_lines=4, rotation=piomatter.Orientation.Normal)
framebuffer = np.asarray(single_frame_img) + 0 # Make a mutable copy
matrix = piomatter.PioMatter(colorspace=piomatter.Colorspace.RGB888Packed,
pinout=piomatter.Pinout.AdafruitMatrixBonnet,
framebuffer=framebuffer,
geometry=geometry)
print("Ctrl-C to exit")
while True:
for x_pixel in range(-total_width-1,full_txt_img.width):
if bottom_half_shift_compensation == 0:
# full paste
single_frame_img.paste(full_txt_img.crop((x_pixel, 0, x_pixel + total_width, total_height)), (0, 0))
else:
# top half
single_frame_img.paste(full_txt_img.crop((x_pixel, 0, x_pixel + total_width, total_height//2)), (0, 0))
# bottom half shift compensation
single_frame_img.paste(full_txt_img.crop((x_pixel, total_height//2, x_pixel + total_width, total_height)), (bottom_half_shift_compensation, total_height//2))
framebuffer[:] = np.asarray(single_frame_img)
matrix.show()
Code Explanation
This example fetches a quote from the Adafruit Quotes API using the requests library. Once fetched the quote is rendered in it's entirety in a single line into a very wide image full_txt_img. This image is too wide to display all at once on the matrix hence the need for scrolling.
The matrix gets initialized and then the code moves to the main loop. Once inside, an inner for loop iterates over horizontal pixel indexes. A matrix sized section of the full_text_img is copied out and pasted into single_frame_img. From there it's copied into the framebuffer and shown on the matrix.
Page last edited February 05, 2025
Mirror Console
Display Configuration
This example will mirror the console's framebuffer to the matrix panel. In order to make it fit better, and to ensure that the requisite /dev/fb0 exists whether or not an HDMI display is plugged in, there will be a modification to the file /boot/firmware/cmdline.txt that adds a video configuration with the smallest allowed display size.
sudo nano /boot/firmware/cmdline.txt
Scroll to the end of the line by pressing end or holding right arrow for a while.
Press space bar to insert a space at the end of the existing line.
Add the following after the space at the end of the existing line.
video=HDMI-A-1:640x480M@60D
Press Ctrl-S to save the file.
Press Ctrl-X to exit.
Then reboot the Pi for it to take effect
sudo reboot
When the Pi boots back up, the file /dev/fb0 should now exist even if you don't have an HDMI display plugged in. If you do have an HDMI display, you'll notice that the text on it is now scaled bigger since we've overridden the display size to be 640x480
As always, you need to activate the virtual environment before running the example. If you haven't already, then activate it like this.
source ~/venvs/blinka_venv/bin/activate
Next you can run the fbmirror_scaled.py script. The script accepts several arguments to configure the panels. The first 3 are specific to the fbmirror examples.
-
--scale- a number to scale the full display down by. What is best depends on what you're showing.2or4are good places to start and then tune it to your content and desired look. -
--x-offset- the number of pixels in the x axis to skip when getting the region to mirror. -
--y-offset- the number of pixels in the y axis to skip when getting the region to mirror.
The remaining arguments are of the configuration options described on the Initialization Config page. The first two are required.
-
--width- the number of pixels wide the total panel is. 128px is for a 2x2 matrix panel. -
--height- the number of pixels tall the total panel is. 64px is for a 2x2 matrix panel.
The rest are optional if you're using default the configuration for everything.
-
--orientation- the rotation angle, must be one ofNormal,CW,CCW,R180. -
--pinout- the pinout to use for the panel(s) e.g.AdafruitMatrixBonnet -
--num-address-lines- the number of address lines. The 64x64 panels we stock use5, all smaller panels use4 -
--num-planes- the color depth, defaults to10. Lower values can improve refresh rate speed. -
--serpentine- the organization of multiple panels, serpentine is default. Use--no-serpentineif your panels are wired in the non-serpentine configuration.
The command should look as follows with appropriate values filled in for your panel:
python fbmirror_scaled.py --scale [scale] --width [width] --height [height] --orientation [orientation]
The values for a 2x2 matrix panel made from 64x32 panels rotated 180 are shown below, adjust them for your panel(s).
python fbmirror_scaled.py --scale 3 --width 128 --height 64 --orientation R180
The code for this example is embedded below. You can download it, or copy/paste the text into a file.
#!/usr/bin/python3
"""
Mirror a scaled copy of the framebuffer to RGB matrices,
A portion of the framebuffer is displayed until the user hits ctrl-c.
Control scale, matrix size, and orientation with command line arguments.
Usage: fbmirror_scaled.py [OPTIONS]
Options:
--x-offset INTEGER The x offset of top left corner of the
region to mirror
--y-offset INTEGER The y offset of top left corner of the
region to mirror
--scale INTEGER The scale factor to reduce the display down
by.
--num-address-lines INTEGER The number of address lines used by the
panels
--num-planes INTEGER The number of bit planes (color depth. Lower
values can improve refresh rate in frames
per second
--orientation [Normal|R180|CCW|CW]
The overall orientation (rotation) of the
panels
--pinout [AdafruitMatrixBonnet|AdafruitMatrixBonnetBGR|AdafruitMatrixHat|AdafruitMatrixHatBGR]
The details of the electrical connection to
the panels
--serpentine / --no-serpentine The organization of multiple panels
--height INTEGER The panel height in pixels
--width INTEGER The panel width in pixels
--help Show this message and exit.
The `/dev/fb0` special file will exist if a monitor is plugged in at boot time,
or if `/boot/firmware/cmdline.txt` specifies a resolution such as
`... video=HDMI-A-1:640x480M@60D`.
"""
import click
import numpy as np
import PIL.Image as Image
import adafruit_blinka_raspberry_pi5_piomatter as piomatter
import adafruit_blinka_raspberry_pi5_piomatter.click as piomatter_click
from adafruit_blinka_raspberry_pi5_piomatter.pixelmappers import simple_multilane_mapper
with open("/sys/class/graphics/fb0/virtual_size") as f:
screenx, screeny = [int(word) for word in f.read().split(",")]
with open("/sys/class/graphics/fb0/bits_per_pixel") as f:
bits_per_pixel = int(f.read())
assert bits_per_pixel == 16
bytes_per_pixel = bits_per_pixel // 8
dtype = {2: np.uint16, 4: np.uint32}[bytes_per_pixel]
with open("/sys/class/graphics/fb0/stride") as f:
stride = int(f.read())
linux_framebuffer = np.memmap('/dev/fb0',mode='r', shape=(screeny, stride // bytes_per_pixel), dtype=dtype)
@click.command
@click.option("--x-offset", "xoffset", type=int, help="The x offset of top left corner of the region to mirror", default=0)
@click.option("--y-offset", "yoffset", type=int, help="The y offset of top left corner of the region to mirror", default=0)
@click.option("--scale", "scale", type=int, help="The scale factor to reduce the display down by.", default=3)
@piomatter_click.standard_options
def main(xoffset, yoffset, scale, width, height, serpentine, rotation, pinout, n_planes, n_temporal_planes, n_addr_lines, n_lanes):
if n_lanes != 2:
pixelmap = simple_multilane_mapper(width, height, n_addr_lines, n_lanes)
geometry = piomatter.Geometry(width=width, height=height, n_planes=n_planes, n_addr_lines=n_addr_lines, n_temporal_planes=n_temporal_planes, n_lanes=n_lanes, map=pixelmap)
else:
geometry = piomatter.Geometry(width=width, height=height, n_planes=n_planes, n_temporal_planes=n_temporal_planes, n_addr_lines=n_addr_lines, rotation=rotation, serpentine=serpentine)
matrix_framebuffer = np.zeros(shape=(geometry.height, geometry.width, 3), dtype=np.uint8)
matrix = piomatter.PioMatter(colorspace=piomatter.Colorspace.RGB888Packed, pinout=pinout, framebuffer=matrix_framebuffer, geometry=geometry)
while True:
tmp = linux_framebuffer[yoffset:yoffset + height * scale, xoffset:xoffset + width * scale]
# Convert the RGB565 framebuffer into RGB888Packed (so that we can use PIL image operations to rescale it)
r = (tmp & 0xf800) >> 8
r = r | (r >> 5)
r = r.astype(np.uint8)
g = (tmp & 0x07e0) >> 3
g = g | (g >> 6)
g = g.astype(np.uint8)
b = (tmp & 0x001f) << 3
b = b | (b >> 5)
b = b.astype(np.uint8)
img = Image.fromarray(np.stack([r, g, b], -1))
img = img.resize((width, height))
matrix_framebuffer[:, :] = np.array(img)
matrix.show()
if __name__ == '__main__':
main()
Code Explanation
After initializing the matrix panel(s), this example mirrors the /dev/fb0 framebuffer using numpy.memmap. Inside the main loop it copies the current values from the mirrored instance into a PIL Image, scales it down to the specified size, then copies it into matrix_framebuffer to be shown on the panel.
Page last edited February 05, 2025
MP4 Video
Playing mp4 video files to the console framebuffer can be done with the VLC application, which is pre-loaded by default in the Raspberry Pi OS. In order to get the video to the matrix panel, we'll use the Mirror Console example from the previous page, so check that out first if you haven't already. The trick is to keep the Mirror Console example running and then play the video so that the video is mirrored to the matrix panels.
You can run the fbmirror_scaled.py script via SSH, or directly from the console with a keyboard. If you run it directly from the console then you'll need to add & to the end of the command to run it in the background so that you can get a new prompt to run the VLC command.
source ~/venvs/blinka_venv/bin/activate cd ~/Adafruit_Blinka_Raspberry_Pi5_PioMatter/examples # Via SSH python fbmirror_scaled.py --scale 16 --width 128 --height 64 --orentation R180 # Direct Console python fbmirror_scaled.py --scale 16 --width 128 --height 64 --orientation R180 &
If you ran it directly in the console, and want to stop the mirroring process you can do so using the ps and kill commands. First run ps and look for the row with "python" in the CMD column, follow that row to the PID column and note the PID number for the process. Then run kill [number] swapping in the pid number of the process.
Once the display is being mirrored, all that's left is to start up the video. We must use the --vout fb argument to tell VLC to send the video output to the framebuffer. It can also be handy to modify the brightness of the video to darken it some if you see lines or other artifacts in the bright regions of your video. That can be done by adding --video-filter=adjust --brightness=0.85 to the command before the video is specified. Change the 0.85 to whatever brightness percentage you want.
The whole command looks like this.
vlc --vout fb --video-filter=adjust --brightness=0.85 your_video_file.mp4
You can stop the video early by pressing Ctrl-C. If you let the entire video play then it will bring you back to the terminal after it's over, but it will still be waiting for you to exit VLC by pressing Ctrl-C.
The code for this is the fbmirror_scaled.py script from the previous page.
Page last edited February 05, 2025
Mirror X Display
Display Configuration
This example will mirror a display running under the X Window System to the matrix panel. Raspberry Pi OS now defaults to the Wayland window system instead of X. In order to use this example, you must configure the Pi 5 to use X for its window system display.
Launch raspi-config with sudo raspi-config.
- Scroll down to Advanced Options and press enter
- Scroll down to Wayland and press enter
- Select the X11 option and press enter
- Press enter for Ok on the dialog confirming the configuration of X11.
- Scroll over to Finish and press enter
- When prompted select Yes to reboot and press enter.
To ensure that the system and any applications running believe that a display exists whether or not an HDMI display is plugged in, there will be a modification to the file /boot/firmware/cmdline.txt that adds a video configuration with the smallest allowed display size.
sudo nano /boot/firmware/cmdline.txt
Scroll to the end of the line by pressing end or holding right arrow for a while.
Press space bar to insert a space at the end of the existing line.
Add the following after the space at the end of the existing line.
video=HDMI-A-1:640x480M@60D
Press Ctrl-S to save the file.
Press Ctrl-X to exit.
Then reboot the Pi for it to take effect
sudo reboot
Run X Display Mirror Example
As always, you need to activate the virtual environment before running the example. If you haven't already, then activate it like this.
source ~/venvs/blinka_venv/bin/activate
Next you can run the xdisplay_mirror.py script. The script accepts several arguments to configure the panels. The first 2 are specific to the xdisplay_mirror.py example.
-
--mirror-region- The region of the display to mirror. x,y,w,h values seperated by commas. If omitted it will mirror the entire screen by default. Example:--mirror-region 0,0,128,128to mirror a 128x128 pixel square of the display at real size on the matrices. -
--x-display- The X display to use. The default is:0. Only needs to be specified if you aren't mirroring the default display. -
--resample-method- The PIL resample method to use when resizing the image to be sent to the panel. Valid values are:nearest,bilinear,lanczos, andbicubic. The default isnearestwhich works best for pixel art style graphics that have been scaled up to fit a larger display. Other methods may look better for different graphics.
The remaining arguments are of the configuration options described on the Initialization Config page. The first two are required.
-
--width- the number of pixels wide the total panel is. 128px is for a 2x2 matrix panel. -
--height- the number of pixels tall the total panel is. 64px is for a 2x2 matrix panel.
The rest are optional if you're using default the configuration for everything.
-
--orientation- the rotation angle, must be one ofNormal,CW,CCW,R180. -
--pinout- the pinout to use for the panel(s) e.g.AdafruitMatrixBonnet -
--num-address-lines- the number of address lines. The 64x64 panels we stock use5, all smaller panels use4 -
--num-planes- the color depth, defaults to10. Lower values can improve refresh rate speed. -
--num-temporal-planes- the temporal dithering control. Valid values are0,2, or4. -
--serpentine- the organization of multiple panels, serpentine is default. Use--no-serpentineif your panels are wired in the non-serpentine configuration.
The values for a 2x2 matrix panel made fro 64x64 matrices rotated 180 are shown below, adjust them for your panel(s).
python xdisplay_mirror.py --pinout AdafruitMatrixHatBGR --width 128 --height 128 --serpentine --num-address-lines 5 --num-planes 8
Once the display is mirrored simply open another terminal or SSH session and launch whatever app you want to mirror.
The code for xdisplay_mirror.py is embedded below. You can download it, or copy/paste the text into a file.
#!/usr/bin/python3
"""
Display a (possibly scaled) X display to a matrix
The display runs until this script exits.
The display doesn't get a keyboard or mouse, so you have to use a program that
will get its input in some other way, such as from a gamepad.
For help with commandline arguments, run `python xdisplay_mirror.py --help`
This example command will mirror the entire display scaled onto a 2x2 grid of 64px panels, total matrix size 128x128.
$ python xdisplay_mirror.py --pinout AdafruitMatrixHatBGR --width 128 --height 128 --serpentine --num-address-lines 5 --num-planes 8
This example command will mirror a 128x128 pixel square from the top left of the display at real size on the same matrix panels
$ python xdisplay_mirror.py --pinout AdafruitMatrixHatBGR --width 128 --height 128 --serpentine --num-address-lines 5 --num-planes 8 --mirror-region 0,0,128,128
"""
import click
import numpy as np
from PIL import Image, ImageGrab
import adafruit_blinka_raspberry_pi5_piomatter as piomatter
import adafruit_blinka_raspberry_pi5_piomatter.click as piomatter_click
from adafruit_blinka_raspberry_pi5_piomatter.pixelmappers import simple_multilane_mapper
RESAMPLE_MAP = {
"nearest": Image.NEAREST,
"bilinear": Image.BILINEAR,
"lanczos": Image.LANCZOS,
"bicubic": Image.BICUBIC
}
@click.command
@click.option("--mirror-region", help="Region of X display to mirror. Comma seperated x,y,w,h. "
"Default will mirror entire display.", default="")
@click.option("--x-display", help="The X display to mirror. Default is :0", default=":0")
@click.option("--brightness", help="The brightness factor of the image output to the matrix",
default=1.0, type=click.FloatRange(min=0.1, max=1.0))
@click.option("--resample-method", type=click.Choice(RESAMPLE_MAP), default="nearest",
help="The resample method for PIL to use when resizing the screen image. Default is nearest")
@piomatter_click.standard_options(n_lanes=2, n_temporal_planes=0)
def main(width, height, serpentine, rotation, pinout, n_planes,
n_temporal_planes, n_addr_lines, n_lanes, mirror_region, x_display, resample_method, brightness):
if n_lanes != 2:
pixelmap = simple_multilane_mapper(width, height, n_addr_lines, n_lanes)
geometry = piomatter.Geometry(width=width, height=height, n_planes=n_planes, n_addr_lines=n_addr_lines,
n_temporal_planes=n_temporal_planes, n_lanes=n_lanes, map=pixelmap)
else:
geometry = piomatter.Geometry(width=width, height=height, n_planes=n_planes, n_addr_lines=n_addr_lines,
n_temporal_planes=n_temporal_planes, rotation=rotation, serpentine=serpentine)
framebuffer = np.zeros(shape=(geometry.height, geometry.width, 3), dtype=np.uint8)
matrix = piomatter.PioMatter(colorspace=piomatter.Colorspace.RGB888Packed, pinout=pinout, framebuffer=framebuffer,
geometry=geometry)
matrix.brightness = brightness
if mirror_region:
mirror_region = tuple(int(_) for _ in mirror_region.split(','))
else:
mirror_region = None
size_measure = ImageGrab.grab(xdisplay=":0")
print(f"Mirroring full display: {size_measure.width}, {size_measure.height}")
while True:
img = ImageGrab.grab(xdisplay=x_display)
if mirror_region is not None:
img = img.crop((mirror_region[0], mirror_region[1], # left,top
mirror_region[0] + mirror_region[2], # right
mirror_region[1] + mirror_region[3])) # bottom
img = img.resize((width, height), RESAMPLE_MAP[resample_method])
framebuffer[:, :] = np.array(img)
matrix.show()
if __name__ == '__main__':
main()
Page last edited February 05, 2025
X Virtual Display
Install Requirements
In addition to everything covered on the Raspberry Pi 5 Setup page, these examples require a few additional requirements to be installed: Xvfb and PyVirtualDisplay. Install them with the following commands.
sudo apt install xvfb source ~/venvs/blinka_venv/bin/activate pip install pyvirtualdisplay
Run Virtual Display Example
This example provides a mirrored display only. This works well if the app that you are mirroring has its own built-in support for handling USB gamepads or other inputs. Some game console emulators have support for controllers built-in, any that do can be used with this script. If your app does not have its own input support, you can use the example from the Mirror X Display page for a different method that allows the keyboard and mouse to work, but it requires different setup and configuration from this one.
As always, you need to activate the virtual environment before running the example. If you haven't already, then activate it like this.
source ~/venvs/blinka_venv/bin/activate
Next you can run the virtualdisplay.py script. The script accepts several arguments to configure the panels. The first 5 are specific to the virtualdisplay example.
-
--scale- The scale factor, larger numbers mean more virtual pixels. Default is 1. -
--backend- The pyvirtualdisplay backend to use. Supported values are xvfb, and xvnc, default is xvfb. -
--extra-args- Extra arguments to pass to the backend server. -
--rfbport- The port number for the--backend xvnc. -
--use-xauth/--no-use-xauth- If a Xauthority file should be created. Default is False.
The remaining arguments are of the configuration options described on the Initialization Config page. The first two are required.
-
--width- the number of pixels wide the total panel is. 128px is for a 2x2 matrix panel. -
--height- the number of pixels tall the total panel is. 64px is for a 2x2 matrix panel.
The rest are optional if you're using default the configuration for everything.
-
--orientation- the rotation angle, must be one ofNormal,CW,CCW,R180. -
--pinout- the pinout to use for the panel(s) e.g.AdafruitMatrixBonnet -
--num-address-lines- the number of address lines. The 64x64 panels we stock use5, all smaller panels use4 -
--num-planes- the color depth, defaults to10. Lower values can improve refresh rate speed. -
n_temporal_planes- Controls the temporal dithering. Valid values are0,2, and4. Cannot be higher thann_planes. The default is0. Using larger values can increase the framerate in some cases experiment with your panels and application. -
--serpentine- the organization of multiple panels, serpentine is default. Use--no-serpentineif your panels are wired in a non-serpentine configuration.
Mirrored App Command
After all of the other arguments, at the end of the command you will include two dashes surrounded by spaces -- , following those you put what ever command is needed to launch the app that you want to mirror including any arguments that it requires.
The command should look as follows with the appropriate values filled in for your panel:
python virtualdisplay.py --scale [scale] --width [width]
--height [height] --orientation [orientation] --num-address-lines
[addrlines] --num-planes [planes] -- [command launching app to mirror]
The values for a 2x2 matrix panel made from 64x64 panels rotated 180 are shown below, adjust them for your panel(s).
python virtualdisplay.py --pinout AdafruitMatrixHatBGR --scale 2 --backend xvfb --width 128 --height 128 --serpentine --num-address-lines 5 --num-planes 4 -- mednafen -snes.xscalefs 1 -snes.yscalefs 1 -snes.xres 128 -video.fs 1 -video.driver softfb /tmp/snesrom.smc
This command is launching Mednafen, a multi-system emulator application. If you're launching something different then replace everything after the double hyphen with your own launch command.
The code for virtualdisplay.py is embedded below. You can download it, or copy/paste the text into a file.
#!/usr/bin/python3
"""
Display a (possibly scaled) X session to a matrix
The display runs until the graphical program exits.
The display doesn't get a keyboard or mouse, so you have to use a program that
will get its input in some other way, such as from a gamepad.
For help with commandline arguments, run `python virtualdisplay.py --help`
This needs additional software to be installed (besides a graphical program to run). At a minimum you have to
install a virtual display server program (xvfb) and the pyvirtualdisplay importable Python module:
$ sudo apt install -y xvfb
$ pip install pyvirtualdisplay
Here's an example for running an emulator using a rom stored in "/tmp/snesrom.smc" on a virtual 128x128 panel made from 4 64x64 panels:
$ python virtualdisplay.py --pinout AdafruitMatrixHatBGR --scale 2 --backend xvfb --width 128 --height 128 --serpentine --num-address-lines 5 --num-planes 4 -- mednafen -snes.xscalefs 1 -snes.yscalefs 1 -snes.xres 128 -video.fs 1 -video.driver softfb /tmp/snesrom.smc
"""
import shlex
from subprocess import Popen
import click
import numpy as np
from pyvirtualdisplay.smartdisplay import SmartDisplay
import adafruit_blinka_raspberry_pi5_piomatter as piomatter
import adafruit_blinka_raspberry_pi5_piomatter.click as piomatter_click
from adafruit_blinka_raspberry_pi5_piomatter.pixelmappers import simple_multilane_mapper
@click.command
@click.option("--scale", type=float, help="The scale factor, larger numbers mean more virtual pixels", default=1)
@click.option("--backend", help="The pyvirtualdisplay backend to use", default="xvfb")
@click.option("--extra-args", help="Extra arguments to pass to the backend server", default="")
@click.option("--rfbport", help="The port number for the --backend xvnc", default=None, type=int)
@click.option("--brightness", help="The brightness factor of the image output to the matrix",
default=1.0, type=click.FloatRange(min=0.1, max=1.0))
@click.option("--use-xauth/--no-use-xauth", help="If a Xauthority file should be created", default=False)
@piomatter_click.standard_options
@click.argument("command", nargs=-1)
def main(scale, backend, use_xauth, extra_args, rfbport, brightness, width, height, serpentine, rotation, pinout,
n_planes, n_temporal_planes, n_addr_lines, n_lanes, command):
kwargs = {}
if backend == "xvnc":
kwargs['rfbport'] = rfbport
if extra_args:
kwargs['extra_args'] = shlex.split(extra_args)
print("xauth", use_xauth)
if n_lanes != 2:
pixelmap = simple_multilane_mapper(width, height, n_addr_lines, n_lanes)
geometry = piomatter.Geometry(width=width, height=height, n_planes=n_planes, n_addr_lines=n_addr_lines,
n_temporal_planes=n_temporal_planes, n_lanes=n_lanes, map=pixelmap)
else:
geometry = piomatter.Geometry(width=width, height=height, n_planes=n_planes, n_addr_lines=n_addr_lines,
n_temporal_planes=n_temporal_planes, rotation=rotation, serpentine=serpentine)
framebuffer = np.zeros(shape=(geometry.height, geometry.width, 3), dtype=np.uint8)
matrix = piomatter.PioMatter(colorspace=piomatter.Colorspace.RGB888Packed, pinout=pinout, framebuffer=framebuffer, geometry=geometry)
matrix.brightness = brightness
with SmartDisplay(backend=backend, use_xauth=use_xauth, size=(round(width*scale),round(height*scale)), manage_global_env=False, **kwargs) as disp, Popen(command, env=disp.env()) as proc:
while proc.poll() is None:
img = disp.grab(autocrop=False)
if img is None:
continue
img = img.resize((width, height))
framebuffer[:, :] = np.array(img)
matrix.show()
if __name__ == '__main__':
main()
Page last edited February 05, 2025
USB HDMI Input
Using the X Virtual Display script from the previous page along with a USB HDMI Capture Adapter and the Linux program guvcview you can mirror any HDMI compatible device to the RGB Matrix panels. For this example we used a Nintendo Switch, but you can plug in whatever device you want to mirror.
Install Requirements
In addition to everything covered on the Raspberry Pi 5 Setup page, these examples require a few additional requirements to be installed: Xvfb, PyVirtualDisplay, and guvcview. Install them with the following commands.
sudo apt install xvfb sudo apt install guvcview source ~/venvs/blinka_venv/bin/activate pip install pyvirtualdisplay
Run the Virtual Display with guvcview
To display the HDMI input to the panels, you can run the virtualdisplay.py script using guvcview as the mirrored app command. See the Run Virtual Display Example and Mirrored App Command sections on the previous page for more details about all possible arguments that can be used for configuring different sizes and amounts of RGB matrices.
By default, guvcview will try to open up two app windows, one with a bunch of configuration options, and the other showing the actual feed from the HDMI input. For mirroring onto the panels, we want to get only the input feed, not the configuration window. The --gui=none argument instructs guvcview to launch only input feed window.
The following command is for 64x64 panels arranged in a 2x2 grid with the no-serpentine arrangement, and in the R180 flipped orientation. Adjust the arguments as needed for your own panel arrangement.
The code for this is the virtualdisplay.py script from the previous page.
python virtualdisplay.py --pinout AdafruitMatrixBonnetBGR --backend xvfb --width 128 --height 128 --no-serpentine --num-address-lines 5 --num-planes 10 --orientation R180 --scale 5 --brightness 0.50 --num-temporal-planes 4 -- guvcview --gui=none
Page last edited February 05, 2025