rgbmatrix

package module
v0.0.0-...-f3ceee8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2023 License: MIT Imports: 13 Imported by: 1

README

go-rpi-rgb-led-matrix GoDoc

Go binding for rpi-rgb-led-matrix an excellent C++ library to control RGB LED displays with Raspberry Pi GPIO.

This library includes the basic bindings to control de LED Matrix directly and also a convenient ToolKit with more high level functions. Also some examples are included to test the library and the configuration.

The Canvas struct implements the image.Image interface from the Go standard library. This makes the interaction with the matrix simple as work with a normal image in Go, allowing the usage of any Go library build around the image.Image interface.

To learn about the configuration and the wiring go to the original library, is highly detailed and well explained.

Installation

The recommended way to add go-rpi-rgb-led-matrix package into your project is:

go get -v github.com/zaggash/go-rpi-rgb-led-matrix

Then you will get an expected error like this:

# github.com/zaggash/go-rpi-rgb-led-matrix
../../../go/pkg/mod/github.com/zaggash/go-rpi-rgb-led-matrix@v0.0.0-20231124140309-bda7481167a0/matrix.go:6:10: fatal error: led-matrix-c.h: No such file or directory
    6 | #include <led-matrix-c.h>
      |          ^~~~~~~~~~~~~~~~
compilation terminated.

This happens because you need to compile the rgbmatrix C bindings. Using the path provided to the go mod package:

cd $GOPATH/go/pkg/mod/github.com/zaggash/go-rpi-rgb-led-matrix@v0.0.0-20180401002551-b26063b3169a/
chmod u+w ./
mkdir ./lib && cd lib
git clone https://github.com/hzeller/rpi-rgb-led-matrix.git
cd rpi-rgb-led-matrix
make -j

This will compile the latest version of the library. The latest version tested with the binding is always the one as the submodule in this repo. Try with that commit if you encounter any issues. This have to be compiled for the destination architecture that will run the Go binary.

After this is done go back to your project and execute the go get command again. This should now work:

$ go get -v github.com/zaggash/go-rpi-rgb-led-matrix
go: finding github.com/zaggash/go-rpi-rgb-led-matrix latest
github.com/zaggash/go-rpi-rgb-led-matrix

Examples

Setting all the pixels to white:

// create a new Matrix instance with the DefaultConfig and if needed the Runtimeconfig
m, _ := rgbmatrix.NewRGBLedMatrix(&rgbmatrix.DefaultConfig, nil)

// create the Canvas, implements the image.Image interface
c := rgbmatrix.NewCanvas(m)
defer c.Close() // don't forgot close the Matrix, if not your leds will remain on
 
// using the standard draw.Draw function we copy a white image onto the Canvas
draw.Draw(c, c.Bounds(), &image.Uniform{color.White}, image.Point{}, draw.Src)

// don't forget call Render to display the new led status
c.Render()

Playing a GIF into your matrix during 30 seconds:

// create a new Matrix instance with the DefaultConfig and if needed the Runtimeconfig
m, _ := rgbmatrix.NewRGBLedMatrix(&rgbmatrix.DefaultConfig, nil)

// create a ToolKit instance
tk := rgbmatrix.NewToolKit(m)
defer tk.Close() // don't forgot close the Matrix, if not your leds will remain on

// open the gif file for reading
file, _ := os.Open("mario.gif")

// play of the gif using the io.Reader
close, _ := tk.PlayGIF(f)
fatal(err)

// we wait 30 seconds and then we stop the playing gif sending a True to the returned chan
time.Sleep(time.Second * 30)
close <- true

The image of the header was recorded using this few lines, the running Mario gif, and three 32x64 pannels.

Check the folder examples folder for more examples

Matrix Emulation

As part of the library an small Matrix emulator is provided. The emulator renderize a virtual RGB matrix on a window in your desktop, without needing a real RGB matrix connected to your computer.

To execute the emulator set the MATRIX_EMULATOR environment variable to 1, then when NewRGBLedMatrix is used, a emulator.Emulator is returned instead of a interface the real board.

License

MIT, see LICENSE

Documentation

Index

Constants

View Source
const MatrixEmulatorENV = "MATRIX_EMULATOR"
View Source
const TerminalMatrixEmulatorENV = "MATRIX_TERMINAL_EMULATOR"

Variables

View Source
var DefaultConfig = HardwareConfig{
	GPIOMapping:            "regular",
	Rows:                   32,
	Cols:                   32,
	ChainLength:            1,
	Parallel:               1,
	PanelType:              "",
	Multiplexing:           0,
	RowAddressType:         0,
	PixelMapperConfig:      "",
	Brightness:             100,
	PWMBits:                11,
	ShowRefreshRate:        false,
	LimitRefresh:           0,
	ScanMode:               Progressive,
	PWMLSBNanoseconds:      130,
	PWMDitherBits:          0,
	DisableHardwarePulsing: false,
	InverseColors:          false,
	RGBSequence:            "RGB",
}

DefaultConfig default configuration

View Source
var DefaultRtConfig = RuntimeConfig{
	GPIOSlowdown: 0,
}

Functions

This section is empty.

Types

type Animation

type Animation interface {
	Next() (image.Image, <-chan time.Time, error)
}

type Canvas

type Canvas struct {
	// contains filtered or unexported fields
}

Canvas is a image.Image representation of a WS281x matrix, it implements image.Image interface and can be used with draw.Draw for example

func NewCanvas

func NewCanvas(m Matrix) *Canvas

NewCanvas returns a new Canvas using the given width and height and creates a new WS281x matrix using the given config

func (*Canvas) At

func (c *Canvas) At(x, y int) color.Color

At returns the color of the pixel at (x, y)

func (*Canvas) Bounds

func (c *Canvas) Bounds() image.Rectangle

Bounds return the topology of the Canvas

func (*Canvas) Clear

func (c *Canvas) Clear() error

Clear set all the leds on the matrix with color.Black

func (*Canvas) Close

func (c *Canvas) Close() error

Close clears the matrix and close the matrix

func (*Canvas) ColorModel

func (c *Canvas) ColorModel() color.Model

ColorModel returns the canvas' color model, always color.RGBAModel

func (*Canvas) Render

func (c *Canvas) Render() error

Render update the display with the data from the LED buffer

func (*Canvas) Set

func (c *Canvas) Set(x, y int, color color.Color)

Set set LED at position x,y to the provided 24-bit color value

type HardwareConfig

type HardwareConfig struct {
	// This can have values such as:
	// * regular          -> The standard mapping of this library
	// * adafruit-hat     -> The Adafruit HAT/Bonnet, that uses this library
	// * adafruit-hat-pwm -> Adafruit HAT with the anti-flicker hardware mod
	// * compute-module   -> Additional 3 parallel chains can be used with the Compute Module.
	// https://github.com/hzeller/rpi-rgb-led-matrix/blob/master/wiring.md#alternative-hardware-mappings
	GPIOMapping string

	// Rows the number of rows supported by the display, so 32 or 16.
	Rows int

	// Cols the number of columns supported by the display, so 32 or 64 .
	Cols int

	// Number of daisy-chained panels.
	ChainLength int

	// Parallel is the number of parallel chains connected to the Pi; in old Pis
	// with 26 GPIO pins, that is 1, in newer Pis with 40 interfaces pins, that
	// can also be 2 or 3. The effective number of pixels in vertical direction is
	// then thus rows * parallel.
	Parallel int

	// Some panels use a different chip-set that requires some initialization.
	// If you don't see any output on your panel, try to set FM6126A
	// Some panels have the FM6127 chip, which is also an option.
	PanelType string

	// The outdoor panels have different multiplexing which allows them to be faster and brighter,
	// but by default their output looks jumbled up.
	// They require some pixel-mapping of which there are a few types you can try and hopefully
	// one of them works for your panel; The default=0 is no mapping ('standard' panels),
	//  while 1, 2, ... are different mappings to try
	// Mux type: 0=direct; 1=Stripe; 2=Checkered...
	Multiplexing int

	// This option is useful for certain 64x64 or 32x16 panels.
	// For 64x64 panels, that only have an A and B address line, you'd use RowAddressType to 1.
	// This is only tested with one panel so far, so if it doesn't work for you, please send a pull request.
	// For 32x16 outdoor panels, that have have 4 address line (A, B, C, D), it is necessary to use RowAddressType to 2.
	RowAddressType int

	// A string describing a sequence of pixel mappers that should be applied
	// to this matrix.
	// Semicolon-separated list of pixel-mappers to arrange pixels.
	// Mapping the logical layout of your boards to your physical arrangement.
	// https://github.com/hzeller/rpi-rgb-led-matrix/blob/master/examples-api-use#remapping-coordinates
	PixelMapperConfig string

	// Brightness is the initial brightness of the panel in percent. Valid range
	// is 1..100
	Brightness int

	// Set PWM bits used for output. Default is 11, but if you only deal with
	// limited comic-colors, 1 might be sufficient. Lower require less CPU and
	// increases refresh-rate.
	PWMBits int

	// This shows the current refresh rate of the LED panel
	// the time to refresh a full picture.
	ShowRefreshRate bool

	// This allows to limit the refresh rate to a particular frequency to approach a fixed refresh rate.
	// The refresh rate will now be adapted to always reach this value between frames,
	// so faster refreshes will be slowed down, but the occasional delayed frame will fit into the time-window as well,
	// thus reducing visible brightness fluctuations.
	// You can play with value a little and reduce until you find a good balance between refresh rate and flicker suppression.
	LimitRefresh int

	// This switches from progressive scan and interlaced scan.
	// The latter might look be a little nicer when you have a very low refresh rate
	// but typically it is more annoying because of the comb-effect
	// 0 = progressive; 1 = interlaced (Default: 0).
	ScanMode ScanMode

	// Change the base time-unit for the on-time in the lowest significant bit in
	// nanoseconds.  Higher numbers provide better quality (more accurate color,
	// less ghosting), but have a negative impact on the frame rate.
	// Good values for full-color display (PWM=11) are somewhere between 100 and 300.
	// If you use reduced bit color (e.g. PWM=1) and have sharp contrast applications,
	// then higher values might be good to minimize ghosting.
	PWMLSBNanoseconds int

	// The lower bits can be time dithered
	// i.e. their brightness contribution is achieved by only showing them some frames
	// This will allow higher refresh rate (or same refresh rate with increased PWMLSBNanoseconds).
	PWMDitherBits int

	// Disable the PWM hardware subsystem to create pulses. Typically, you don't
	// want to disable hardware pulsing, this is mostly for debugging and figuring
	// out if there is interference with the sound system.
	// This won't do anything if output enable is not connected to GPIO 18 in
	// non-standard wirings.
	DisableHardwarePulsing bool

	// Switch if your matrix has inverse colors on.
	InverseColors bool

	// These are if you have a different kind of LED panel where the Red, Green and Blue LEDs are mixed up
	// Default: "RGB"
	RGBSequence string
}

HardwareConfig rgb-led-matrix configuration

type Matrix

type Matrix interface {
	Geometry() (width, height int)
	At(position int) color.Color
	Set(position int, c color.Color)
	Apply([]color.Color) error
	Render() error
	Close() error
	GetBrightness() int
	SetBrightness(int)
}

Matrix is an interface that represent any RGB matrix, very useful for testing

func NewRGBLedMatrix

func NewRGBLedMatrix(config *HardwareConfig, rtconfig *RuntimeConfig) (c Matrix, err error)

NewRGBLedMatrix returns a new matrix using the given size and config

type RGBLedMatrix

type RGBLedMatrix struct {
	Config   *HardwareConfig
	RtConfig *RuntimeConfig
	// contains filtered or unexported fields
}

RGBLedMatrix matrix representation for ws281x

func (*RGBLedMatrix) Apply

func (c *RGBLedMatrix) Apply(leds []color.Color) error

Apply set all the pixels to the values contained in leds

func (*RGBLedMatrix) At

func (c *RGBLedMatrix) At(position int) color.Color

At return an Color which allows access to the LED display data as if it were a sequence of 24-bit RGB values.

func (*RGBLedMatrix) Close

func (c *RGBLedMatrix) Close() error

Close finalizes the ws281x interface

func (*RGBLedMatrix) Geometry

func (c *RGBLedMatrix) Geometry() (width, height int)

Geometry returns the width and the height of the matrix

func (*RGBLedMatrix) GetBrightness

func (c *RGBLedMatrix) GetBrightness() int

GetBrightness returns the current brightness setting of the matrix

func (*RGBLedMatrix) Initialize

func (c *RGBLedMatrix) Initialize() error

Initialize initialize library, must be called once before other functions are called.

func (*RGBLedMatrix) Render

func (c *RGBLedMatrix) Render() error

Render update the display with the data from the LED buffer

func (*RGBLedMatrix) Set

func (c *RGBLedMatrix) Set(position int, color color.Color)

Set set LED at position x,y to the provided 24-bit color value.

func (*RGBLedMatrix) SetBrightness

func (c *RGBLedMatrix) SetBrightness(brightness int)

SetBrightness sets a new brightness setting to the matrix

type RuntimeConfig

type RuntimeConfig struct {
	// The Raspberry Pi starting with Pi2 are putting out data too fast.
	// In this case, you want to slow down writing to GPIO.
	// Zero for this parameter means 'no slowdown'.
	// The default 1 (one) typically works fine
	// You have to even go further by setting it to 2 (two).
	// If you have a Raspberry Pi with a slower processor (Model A, A+, B+, Zero), then a value of 0 (zero) might work and is desirable.
	//A Raspberry Pi 3 or Pi4 might even need higher values for the panels to be happy.
	GPIOSlowdown int
}

RuntimeConfig

type ScanMode

type ScanMode int8
const (
	Progressive ScanMode = 0
	Interlaced  ScanMode = 1
)

type ToolKit

type ToolKit struct {
	// Canvas is the Canvas wrapping the Matrix, if you want to instanciate
	// a ToolKit with a custom Canvas you can use directly the struct,
	// without calling NewToolKit
	Canvas *Canvas

	// Transform function if present is applied just before draw the image to
	// the Matrix, this is a small example:
	//	tk.Transform = func(img image.Image) *image.NRGBA {
	//		return imaging.Fill(img, 64, 96, imaging.Center, imaging.Lanczos)
	//	}
	Transform func(img image.Image) *image.NRGBA
}

ToolKit is a convinient set of function to operate with a led of Matrix

func NewToolKit

func NewToolKit(m Matrix) *ToolKit

NewToolKit returns a new ToolKit wrapping the given Matrix

func (*ToolKit) Close

func (tk *ToolKit) Close() error

Close close the toolkit and the inner canvas

func (*ToolKit) PlayAnimation

func (tk *ToolKit) PlayAnimation(a Animation) error

PlayAnimation play the image during the delay returned by Next, until an err is returned, if io.EOF is returned, PlayAnimation finish without an error

func (*ToolKit) PlayGIF

func (tk *ToolKit) PlayGIF(r io.Reader) (chan bool, error)

PlayGIF reads and draw a gif file from r. It use the contained images and delays and loops over it, until a true is sent to the returned chan

func (*ToolKit) PlayImage

func (tk *ToolKit) PlayImage(i image.Image, delay time.Duration) error

PlayImage draws the given image during the given delay

func (*ToolKit) PlayImageUntil

func (tk *ToolKit) PlayImageUntil(i image.Image, notify <-chan time.Time) error

PlayImageUntil draws the given image until is notified to stop

func (*ToolKit) PlayImages

func (tk *ToolKit) PlayImages(images []image.Image, delay []time.Duration, loop int) chan bool

PlayImages draws a sequence of images during the given delays, the len of images should be equal to the len of delay. If loop is true the function loops over images until a true is sent to the returned chan

Directories

Path Synopsis
examples
pxl

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL