rpi-led-matrix

repository·main·Indexed 41 days ago

https://github.com/alexeden/rpi-led-matrix

Node.js and TypeScript bindings for the rpi-rgb-led-matrix library, providing high-performance, double-buffered rendering for RGB LED matrices connected to a Raspberry Pi. Version 1.15.0 includes a drawing API with method chaining, support for custom fonts via the Font class, and layout utilities for text rendering and alignment.

Tokens
6.7K
Snippets
24
Records
31
Agent score
50%

What's inside rpi-led-matrix

  1. Import rpi-led-matrix

    main

    You can import the library using standard CommonJS require or ESM import syntax depending on your project setup.

    // In a .ts file
    import * as matrix from 'rpi-led-matrix';
    
    // Or, in a .js file
    const matrix = require('rpi-led-matrix');
  2. Set up local development with automatic sync to Raspberry Pi

    main

    You can develop locally on your machine and automatically sync changes to your Raspberry Pi.

    1. Prerequisites: Ensure you have passwordless SSH access to your Pi.
    2. Clone: Clone the repository with submodules onto both your local machine and the Pi.
    3. Install: Run npm install in both locations.
    4. Configure Sync: Create a sync.config.json file on your local machine with the following structure:
      {
        "username": "<username>",
        "hostname": "<hostname or IP address of your Pi>",
        "directory": "<parent directory on Pi into which the repo was cloned>",
        "quiet": false
      }
    5. Workflow:
      • On Local Machine: Run npm run sync-changes. Any changes to /src or /examples will be automatically uploaded to the Pi.
      • On Raspberry Pi: Run npm run build-changes. This will automatically rebuild the changes pushed from your local machine.

    Troubleshooting: If npm install fails with TypeError: cannot use a string pattern on a bytes-like object, try switching your environment to Python 2.7.

    {
      "username": "<username>",
      "hostname": "<hostname or IP address of your Pi>",
      "directory": "<parent directory on Pi into which the repo was cloned>",
      "quiet": false
    }
  3. Install rpi-led-matrix via npm

    main

    Install the package using npm. Note that if you are installing on a machine that is not a Raspberry Pi, you will see node-gyp warnings regarding the compilation of the addon module; these are expected and will disappear when installed on an actual Raspberry Pi.

    $ npm install --save rpi-led-matrix
  4. Initialize a LedMatrix instance

    main

    To create a matrix instance, use the LedMatrix constructor. Because the module is a native C++ addon, LedMatrix is provided as an interface. Since the MatrixOptions and RuntimeOptions interfaces are large, use the static helper methods LedMatrix.defaultMatrixOptions() and LedMatrix.defaultRuntimeOptions() to generate configuration objects with default values, then extend them with your specific hardware requirements.

    import { LedMatrix } from 'rpi-led-matrix';
    
    const matrix = new LedMatrix(
      LedMatrix.defaultMatrixOptions(),
      LedMatrix.defaultRuntimeOptions()
    );
  5. Run project examples

    main

    To run the provided examples, you must first clone the repository with submodules and install dependencies.

    1. Clone the repo:
      git clone --recurse-submodules https://github.com/alexeden/rpi-led-matrix
      cd rpi-led-matrix
      npm i
    2. Configure your matrix: Update examples/_config.ts with your specific hardware configuration. All examples rely on this file.
    3. Execute an example: Use tsx to run examples. Note that running hardware-interfacing code on a Raspberry Pi typically requires sudo.

    Example command to run the kitchen-sink example:

    sudo npx tsx examples/kitchen-sink.ts
  6. Configure MatrixOptions

    main

    The MatrixOptions interface defines the physical and electrical configuration of your LED hardware. You should extend the defaults provided by LedMatrix.defaultMatrixOptions().

    Key configuration concepts:

    • Hardware Mapping: Use the GpioMapping enum to specify your connection type (e.g., GpioMapping.AdafruitHatPwm).
    • Pixel Mapping: For complex physical configurations, use LedMatrixUtils.encodeMappers() to generate the required pixelMapperConfig string.
    • Enums: Use provided enums for discrete values like ScanMode, MuxType, and RowAddressType to ensure type safety.
    import {
      LedMatrix,
      GpioMapping,
      LedMatrixUtils,
      PixelMapperType,
    } from 'rpi-led-matrix';
    
    const matrix = new LedMatrix(
      {
        ...LedMatrix.defaultMatrixOptions(),
        rows: 32,
        cols: 64,
        chainLength: 2,
        hardwareMapping: GpioMapping.AdafruitHatPwm,
        pixelMapperConfig: LedMatrixUtils.encodeMappers({
          type: PixelMapperType.U,
        }),
      },
      {
        ...LedMatrix.defaultRuntimeOptions(),
        gpioSlowdown: 1,
      }
    );
  7. Align text using HorizontalAlignment and VerticalAlignment

    main

    The LayoutUtils class uses two enums to control how text blocks are positioned within a container:

    HorizontalAlignment

    • Left: Aligns text to the start of the container (x=0).
    • Center: Centers the text line horizontally within the container width.
    • Right: Aligns text to the end of the container (x = containerW - lineW).

    VerticalAlignment

    • Top: Aligns the text block to the top of the container (y=0).
    • Middle: Centers the text block vertically within the container height.
    • Bottom: Aligns the text block to the bottom of the container (y = containerH - blockH).
  8. Use the `afterSync` hook for time-dependent animations

    main

    To create animations that depend on time (like pulsing or moving elements), use the afterSync method on an LedMatrixInstance. This method accepts a SyncHook callback that is automatically executed after every matrix sync.

    Callback Signature: type SyncHook = (matrix: LedMatrixInstance, dt: number, t: number) => void;

    • matrix: The current LedMatrixInstance.
    • dt: Time elapsed since the previous sync (in milliseconds).
    • t: Monotonically-increasing system clock time (in milliseconds).

    CRITICAL: When calling matrix.sync() inside the afterSync callback to create a continuous animation loop, you must wrap it in a setTimeout(() => matrix.sync(), 0). Failing to do this will cause a stack overflow error because the calls will occur synchronously on the same stack.

    This pattern is similar to requestAnimationFrame in web development.

    // Example: Creating a continuous animation loop
    matrix.afterSync((mat, dt, t) => {
      // 1. Perform your drawing logic here
      mat.fgColor(0xff0000).setPixel(0, 0);
    
      // 2. Schedule the next sync using setTimeout to avoid stack overflow
      setTimeout(() => mat.sync(), 0);
    });
    
    // Start the initial sync
    matrix.sync();
  9. Draw shapes and text using LedMatrixInstance

    main

    The LedMatrixInstance provides a drawing API. Most methods follow a getter/setter pattern: calling a method without arguments returns the current value, while calling it with an argument sets the value and returns the instance itself. This allows for method chaining.

    Important Note: Changes are not immediately visible on the hardware. You must call .sync() to commit your drawing operations to the display.

    matrix
      .clear() // clear the display
      .brightness(100) // set the panel brightness to 100%
      .fgColor(0x0000ff) // set the active color to blue
      .fill() // color the entire display blue
      .fgColor(0xffff00) // set the active color to yellow
      .drawCircle(matrix.width() / 2, matrix.height() / 2, matrix.width() / 2 - 1)
      .drawRect(
        matrix.width() / 4,
        matrix.height() / 4,
        matrix.width() / 2,
        matrix.height() / 2
      )
      .fgColor({ r: 255, g: 0, b: 0 }) // sets the active color to red
      .drawLine(0, 0, matrix.width(), matrix.height())
      .drawLine(matrix.width() - 1, 0, 0, matrix.height() - 1)
      .sync(); // commit changes to the display
  10. Configure RuntimeOptions for process management

    main

    The RuntimeOptions interface controls how the library manages the background thread and system privileges.

    • daemon: Controls background execution using RuntimeFlag.
      • RuntimeFlag.Disabled: You must call StartRefresh() manually.
      • RuntimeFlag.On or RuntimeFlag.Off: The thread is started automatically.
    • dropPrivileges: If set to RuntimeFlag.On, the process drops from root to daemon after hardware initialization.
    • gpioSlowdown: Adjusts GPIO write speed for newer Raspberry Pi models (Pi2+) to prevent data overflow. Values range from 0 (no slowdown) to 4.
    const runtimeOptions: RuntimeOptions = {
      daemon: RuntimeFlag.Off,
      doGpioInit: true,
      dropPrivileges: RuntimeFlag.On,
      gpioSlowdown: 1
    };
  11. Configure MatrixOptions for LED panels

    main

    The MatrixOptions interface defines the physical and electrical configuration of your LED matrix. Use this to specify panel dimensions, multiplexing types, and hardware-specific settings like GPIO mapping and PWM precision.

    Key configuration properties include:

    • brightness: Initial brightness percentage (default: 100).
    • chainLength: Number of daisy-chained panels (default: 1).
    • cols & rows: Dimensions of a single panel (e.g., 32 cols, 32 rows).
    • multiplexing: The MuxType required by your panel.
    • hardwareMapping: The GpioMapping used (e.g., GpioMapping.Regular or GpioMapping.AdafruitHat).
    • pixelMapperConfig: A string representing the pixel mapper arrangement. Use LedMatrixUtils.encodeMappers() to generate this.
    • pwmBits: Precision of PWM (1-11, default: 11).
    • scanMode: ScanMode.Progressive or ScanMode.Interlaced.
    const matrixOptions: MatrixOptions = {
      brightness: 100,
      chainLength: 1,
      cols: 64,
      rows: 32,
      multiplexing: MuxType.Direct,
      hardwareMapping: GpioMapping.Regular,
      scanMode: ScanMode.Progressive,
      // ... other options
    };
  12. Reference: Core Classes and Utilities

    main

    The following classes and utility modules are exported for controlling the LED matrix and rendering content:

    Core Classes:

    • LedMatrix: The main class used to instantiate the matrix.
    • Font: Wraps native font entities for text rendering.

    Utility Modules:

    • LedMatrixUtils: Helper methods for matrix configuration.
    • LayoutUtils: High-level functionality for easy text rendering. Includes support for:
      • MappedGlyph
      • Line
      • HorizontalAlignment
      • VerticalAlignment