FWIW, here is the code that I use on my Teensy 4.1 using the built-in SD card reader, the Smartmatrix v5 board for Teensy 4.x, and with the Adafruit 64x64 RGB LED Matrix - 2.5mm Pitch - 1/32 Scan display.
If you have a different sized display, you will need to change kMatrixWidth or kMatrixHeight. I set this up so I can use the same SD card with different sub-directories depending on the screen size (32x32 is /gifs32/, 64x64 is /gifs64/ and 64x32 is /gifs/):
/*
* Animated GIFs Display Code for SmartMatrix and HUB75 RGB LED Panels
*
* Uses SmartMatrix Library written by Louis Beaudoin at pixelmatix.com
*
* Written by: Craig A. Lindley
*
* Copyright (c) 2014 Craig A. Lindley
* Refactoring by Louis Beaudoin (Pixelmatix)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* This SmartMatrix Library example displays GIF animations loaded from a SD Card connected to the Teensy 3/4 and ESP32
*
* This example requires SmartMatrix Library 4.0 and AnimatedGIF Library to be installed, you can do this from Arduino Library Manager
* - https://github.com/pixelmatix/SmartMatrix
* - https://github.com/bitbank2/AnimatedGIF
*
* The example can be modified to drive displays other than SmartMatrix by replacing SmartMatrix Library calls in setup() and
* the *Callback() functions with calls to a different library (look for the USE_SMARTMATRIX and ENABLE_SCROLLING blocks and replace)
*
* Wiring is on the default Teensy 3.2 SPI pins, and chip select can be on any GPIO,
* set by defining SD_CS in the code below. For Teensy 3.5/3.6/4.1 with the onboard SDIO, SD_CS should be the default BUILTIN_SDCARD
* Function | Pin
* DOUT | 11
* DIN | 12
* CLK | 13
* CS (default) | 15
*
* Wiring for ESP32 follows the default for the ESP32 SD Library, see: https://github.com/espressif/arduino-esp32/tree/master/libraries/SD
*
* This code first looks for .gif files in the /gifs/ directory
* (customize below with the GIF_DIRECTORY definition) then plays random GIFs in the directory,
* looping each GIF for DISPLAY_TIME_SECONDS
*
* This example is meant to give you an idea of how to add GIF playback to your own sketch.
* For a project that adds GIF playback with other features, take a look at
* Light Appliance and Aurora:
* https://github.com/CraigLindley/LightAppliance
* https://github.com/pixelmatix/aurora
*
* If you find any GIFs that won't play properly, please attach them to a new
* Issue post in the GitHub repo here:
* https://github.com/pixelmatix/AnimatedGIFs/issues
*/
/*
* CONFIGURATION:
* - Uncomment one line to select your MatrixHardware configuration - configuration header needs to be included before <SmartMatrix.h>
* - update the "SmartMatrix configuration and memory allocation" section to match the width and height and other configuration of your display
* - Note for 128x32 and 64x64 displays with Teensy 3.2 - need to reduce RAM:
* set kRefreshDepth=24 and kDmaBufferRows=2 or set USB Type: "None" in Arduino,
* decrease refreshRate in setup() to 90 or lower to get good an accurate GIF frame rate
* - Set the chip select pin for your board. On Teensy 3.5/3.6/4.1, the onboard microSD CS pin is "BUILTIN_SDCARD"
* - For ESP32 used with large panels, you don't need to lower the refreshRate, but you can lower the frameRate (number of times the refresh buffer
* is updaed with new data per second), giving more time for the CPU to decode the GIF.
* Use matrix.setMaxCalculationCpuPercentage() or matrix.setCalcRefreshRateDivider()
*/
#if defined(ARDUINO_TEENSY40) || defined(ARDUINO_TEENSY41)
#include <MatrixHardware_Teensy4_ShieldV5.h> // SmartLED Shield for Teensy 4 (V5)
#elif defined(ARDUINO_TEENSY35) || defined(ARDUINO_TEENSY36)
#include <MatrixHardware_Teensy4_ShieldV4.h> // SmartLED Shield for Teensy 4 (V5)
#else
#error "Include the correct header for the microprocessor"
#endif
#include <SmartMatrix.h>
#include <SD.h>
#include <GifDecoder.h>
#include "FilenameFunctions.h"
#define DISPLAY_TIME_SECONDS 10
#define NUMBER_FULL_CYCLES 100
#define USE_SMARTMATRIX 1
#define ENABLE_SCROLLING 1
// range 0-255
const int defaultBrightness = 255;
const rgb24 COLOR_BLACK = {
0, 0, 0 };
#if (USE_SMARTMATRIX == 1)
/* SmartMatrix configuration and memory allocation */
#define COLOR_DEPTH 24 // Choose the color depth used for storing pixels in the layers: 24 or 48
// (24 is good for most sketches - If the sketch uses type `rgb24` directly,
// COLOR_DEPTH must be 24)
#define kMatrixWidth 64U // Set to the width of your display, must be a multiple of 8
#define kMatrixHeight 64U // Set to the height of your display
const uint8_t kRefreshDepth = 36; // Tradeoff of color quality vs refresh rate, max brightness, and RAM usage.
// 36 is typically good, drop down to 24 if you need to.
// On Teensy, multiples of 3, up to 48: 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48.
// On ESP32: 24, 36, 48
const uint8_t kDmaBufferRows = 4; // known working: 2-4, use 2 to save RAM, more to keep from dropping frames
// and automatically lowering refresh rate. (This isn't used on ESP32, leave as default)
// Choose the configuration that matches your panels. See more details in
// MatrixCommonHub75.h and the docs: https://github.com/pixelmatix/SmartMatrix/wiki
#if kMatrixHeight == 64
const uint8_t kPanelType = SM_PANELTYPE_HUB75_64ROW_MOD32SCAN;
#elif kMatrixHeight == 32
const uint8_t kPanelType = SM_PANELTYPE_HUB75_32ROW_MOD16SCAN;
#elif kMatrixHeight == 16
const uint8_t kPanelType = SM_PANELTYPE_HUB75_16ROW_MOD8SCAN;
#else
#error "Update setting kPanelType"
#endif
// see docs for options: https://github.com/pixelmatix/SmartMatrix/wiki
const uint32_t kMatrixOptions = (SM_HUB75_OPTIONS_NONE);
const uint8_t kBackgroundLayerOptions = (SM_BACKGROUND_OPTIONS_NONE);
const uint8_t kScrollingLayerOptions = (SM_SCROLLING_OPTIONS_NONE);
SMARTMATRIX_ALLOCATE_BUFFERS(matrix, kMatrixWidth, kMatrixHeight, kRefreshDepth, kDmaBufferRows, kPanelType, kMatrixOptions);
SMARTMATRIX_ALLOCATE_BACKGROUND_LAYER(backgroundLayer, kMatrixWidth, kMatrixHeight, COLOR_DEPTH, kBackgroundLayerOptions);
#if (ENABLE_SCROLLING == 1)
SMARTMATRIX_ALLOCATE_SCROLLING_LAYER(scrollingLayer, kMatrixWidth, kMatrixHeight, COLOR_DEPTH, kScrollingLayerOptions);
#endif
#endif
/* template parameters are maxGifWidth, maxGifHeight, lzwMaxBits
*
* lzwMaxBits is included for backwards compatibility reasons, but isn't used anymore
*/
GifDecoder<kMatrixWidth, kMatrixHeight, 12> decoder;
// Chip select for SD card
#if defined(ESP32)
#define SD_CS 5
#elif defined (ARDUINO)
#define SD_CS BUILTIN_SDCARD
//#define SD_CS 15
#endif
// Use different directories for 32x32, 64x32, and 64x64
#if (kMatrixWidth == 32) && (kMatrixHeight == 32)
#define GIF_SUFFIX "32"
#elif (kMatrixWidth == 64) && (kMatrixHeight == 64)
#define GIF_SUFFIX "64"
#else
#define GIF_SUFFIX ""
#endif
#if defined(ESP32)
// ESP32 SD Library can't handle a trailing slash in the directory name
#define GIF_SUFFIX2 ""
#else
// Teensy SD Library requires a trailing slash in the directory name
#define GIF_SUFFIX2 "/"
#endif
#define GIF_DIRECTORY "/gifs" GIF_SUFFIX GIF_SUFFIX2
int num_files;
void screenClearCallback(void) {
#if (USE_SMARTMATRIX == 1)
backgroundLayer.fillScreen({0,0,0});
#endif
}
void updateScreenCallback(void) {
#if (USE_SMARTMATRIX == 1)
backgroundLayer.swapBuffers();
#endif
}
void drawPixelCallback(int16_t x, int16_t y, uint8_t red, uint8_t green, uint8_t blue) {
#if (USE_SMARTMATRIX == 1)
backgroundLayer.drawPixel(x, y, {red, green, blue});
#endif
}
// Setup method runs once, when the sketch starts
void setup() {
decoder.setScreenClearCallback(screenClearCallback);
decoder.setUpdateScreenCallback(updateScreenCallback);
decoder.setDrawPixelCallback(drawPixelCallback);
decoder.setFileSeekCallback(fileSeekCallback);
decoder.setFilePositionCallback(filePositionCallback);
decoder.setFileReadCallback(fileReadCallback);
decoder.setFileReadBlockCallback(fileReadBlockCallback);
// NOTE: new callback function required after we moved to using the external AnimatedGIF library to decode GIFs
decoder.setFileSizeCallback(fileSizeCallback);
Serial.begin(115200);
// give time for USB Serial to be ready
delay(1000);
Serial.println ("Starting AnimatedGIFs Sketch");
Serial.print ("Matrix Width = "); Serial.println (kMatrixWidth);
Serial.print ("Matrix Height = "); Serial.println (kMatrixHeight);
Serial.print ("Refresh depth = "); Serial.println (kRefreshDepth);
Serial.print ("DMA buffer rows = "); Serial.println (kDmaBufferRows);
Serial.print ("Gif directory = "); Serial.println (GIF_DIRECTORY);
Serial.print ("USE_SMARTMATRIX = "); Serial.println (USE_SMARTMATRIX);
Serial.print ("ENABLE_SCROLLING = "); Serial.println (ENABLE_SCROLLING);
Serial.println ("");
#if (USE_SMARTMATRIX == 1)
// Initialize matrix
matrix.addLayer(&backgroundLayer);
#if (ENABLE_SCROLLING == 1)
matrix.addLayer(&scrollingLayer);
#endif
matrix.setBrightness(defaultBrightness);
// for large panels, may want to set the refresh rate lower to leave more CPU time to decoding GIFs (needed if GIFs are playing back slowly)
//matrix.setRefreshRate(90);
#if !defined(ESP32)
matrix.begin();
#endif
#if defined(ESP32)
// for large panels on ESP32, may want to set the max percentage time dedicated to updating the refresh frames lower, to leave more CPU time to decoding GIFs (needed if GIFs are playing back slowly)
//matrix.setMaxCalculationCpuPercentage(50);
// alternatively, for large panels on ESP32, may want to set the calculation refresh rate divider lower to leave more CPU time to decoding GIFs (needed if GIFs are playing back slowly) - this has the same effect as matrix.setMaxCalculationCpuPercentage() but is set with a different parameter
//matrix.setCalcRefreshRateDivider(4);
// The ESP32 SD Card library is going to want to malloc about 28000 bytes of DMA-capable RAM, make sure at least that much is left free
matrix.begin(28000);
#endif
// Clear screen
backgroundLayer.fillScreen(COLOR_BLACK);
backgroundLayer.swapBuffers();
#endif
if(initFileSystem(SD_CS) < 0) {
#if (ENABLE_SCROLLING == 1)
scrollingLayer.start("No SD card", -1);
#endif
Serial.println("No SD card");
while(1);
}
// Determine how many animated GIF files exist
num_files = enumerateGIFFiles(GIF_DIRECTORY, true);
if(num_files < 0) {
#if (ENABLE_SCROLLING == 1)
scrollingLayer.start("No gifs directory", -1);
#endif
Serial.println("No gifs directory");
while(1);
}
if(!num_files) {
#if (ENABLE_SCROLLING == 1)
scrollingLayer.start("Empty gifs directory", -1);
#endif
Serial.println("Empty gifs directory");
while(1);
}
}
void loop() {
static unsigned long displayStartTime_millis;
static int nextGIF = 1; // we haven't loaded a GIF yet on first pass through, make sure we do that
unsigned long now = millis();
static int index = 0;
#if 1
// default behavior is to play the gif for DISPLAY_TIME_SECONDS or for NUMBER_FULL_CYCLES, whichever comes first
if((now - displayStartTime_millis) > (DISPLAY_TIME_SECONDS * 1000) || decoder.getCycleNumber() > NUMBER_FULL_CYCLES)
nextGIF = 1;
#else
// alt behavior is to play the gif until both DISPLAY_TIME_SECONDS and NUMBER_FULL_CYCLES have passed
if((now - displayStartTime_millis) > (DISPLAY_TIME_SECONDS * 1000) && decoder.getCycleNumber() > NUMBER_FULL_CYCLES)
nextGIF = 1;
#endif
if(nextGIF)
{
nextGIF = 0;
if (openGifFilenameByIndex(GIF_DIRECTORY, index) >= 0) {
// Can clear screen for new animation here, but this might cause flicker with short animations
// matrix.fillScreen(COLOR_BLACK);
// matrix.swapBuffers();
// start decoding, skipping to the next GIF if there's an error
if(decoder.startDecoding() < 0) {
nextGIF = 1;
return;
}
// Calculate time in the future to terminate animation
displayStartTime_millis = now;
}
// get the index for the next pass through
if (++index >= num_files) {
index = 0;
}
}
if(decoder.decodeFrame() < 0) {
// There's an error with this GIF, go to the next one
nextGIF = 1;
}
}
// HISTORY
// $Log: AnimatedGifs_64x64.ino,v $
// Revision 1.8 2022/02/25 20:59:37 michaelmeissner
// Use correct panel type.
//
// Revision 1.7 2022/02/25 20:57:25 michaelmeissner
// Fix typo (width => height in selecting sizes)
//
// Revision 1.6 2022/02/25 20:50:13 michaelmeissner
// Rework setting options, add 64 row support.
//
// Revision 1.5 2022/02/21 04:47:37 michaelmeissner
// Use #define instead of const uint8_t for width & height.
//
// Revision 1.4 2022/02/21 04:31:31 michaelmeissner
// Use different gifs directory for 32x32 and 64x64.
//
// Revision 1.3 2022/02/21 02:59:15 michaelmeissner
// Print out compiled height, width, refresh depth, and DMA buffer rows.
//
// Revision 1.2 2022/02/21 02:42:27 michaelmeissner
// Add Teensy 3.5/3.6/4.0/4.1 support; Change size to 64x64.
//
// Revision 1.1 2022/02/21 02:32:40 michaelmeissner
// Initial version.
//