unicorn-hat
A Rust library for controlling the Pimoroni Unicorn HAT (8x8 LED matrix) on Raspberry Pi.
Features
- Pixel Control: Set pixels by coordinate (x, y) or raw index
- Color Models: RGB8 and HSV with seamless conversion
- Display Control: Brightness adjustment and rotation (0°, 90°, 180°, 270°)
- Drawing Primitives: Lines, rectangles, filled shapes
- Gradients: Horizontal and vertical color gradients
- Color Palettes: Built-in palettes with value-to-color mapping
- Hardware Abstraction: BGR format and zigzag LED mapping handled automatically
Installation
Add to your Cargo.toml:
[]
= "0.1"
System Requirements
Hardware:
- Pimoroni Unicorn HAT (8×8, NOT the HD version)
- Raspberry Pi with 40-pin GPIO header
System Setup:
# Install dependencies
# Enable SPI
# Navigate to: Interface Options -> SPI -> Enable
Quick Start
use ;
Run with sudo:
Examples
Rainbow Gradient (HSV)
use ;
let mut hat = new?;
for x in 0..8
hat.display?;
Drawing Primitives
use ;
let mut hat = new?;
// Draw a horizontal line
draw_hline?;
// Draw a filled rectangle
fill_rect?;
hat.display?;
Color Gradients
use ;
let mut hat = new?;
// Horizontal gradient from red to blue
gradient_h?;
hat.display?;
High-Level Features
For text rendering, scrolling animations, and frame buffers, see the companion crate:
[]
= "0.1"
= "0.1"
See the unicorn-hat-extras documentation for details.
API Overview
Core Types
UnicornHat- Main controllerRGB8- 8-bit RGB color (0-255 per channel)HSV- Hue/Saturation/Value color modelRotate- Display rotationOrigin- Coordinate system origin (TopLeft or BottomLeft)
Main Methods
// Initialization
let mut hat = new?;
// Pixel operations
hat.set_pixel?;
hat.get_pixel?;
hat.fill;
hat.clear;
// Display
hat.display?;
// Configuration
hat.set_brightness; // 0-255
hat.set_rotation;
// Bulk operations
hat.set_all?;
let grid = hat.get_all?;
Color Constants
RGB8::BLACK, RGB8::WHITE, RGB8::RED, RGB8::GREEN, RGB8::BLUE, RGB8::YELLOW, RGB8::CYAN, RGB8::MAGENTA, RGB8::ORANGE, RGB8::PURPLE
Permissions
The library requires hardware access. You have two options:
Option 1: Run with sudo (Development)
Option 2: Set capabilities (Production)
Note: Capabilities must be reset after each rebuild.
Examples
Run the included examples:
Documentation
Generate full API documentation:
Hardware Details
- GPIO Pin: 18 (PWM)
- LED Type: WS2812
- LED Count: 64 (8×8)
- Frequency: 800 kHz
- Color Format: BGR (handled internally)
Known Limitations
- Audio Conflict: PWM conflicts with 3.5mm audio jack (use HDMI or USB audio)
- Single Instance: Only one process can control the HAT at a time
- Requires Root: Needs
sudoorCAP_SYS_RAWIOcapability
License
MIT License - see LICENSE for details.
Links
See Also
- unicorn-hat-extras - Text, scrolling, and animations