How to Drive WS2812 LEDs (SPI-to-WS2812)
Overview
Driving WS2812 Light-Emitting Diodes (LEDs) requires a precise, timing-specific signal that cannot be directly generated by standard communication protocols like Serial Peripheral Interface (SPI). WS2812 LEDs use a single-wire protocol with strict timing requirements to control the color and brightness of each LED. Without proper encoding, these timing demands can lead to unreliable performance or visible artifacts in the LED strip's behavior.
By using an SPI-to-WS2812 encoder, signals are translated into the required format efficiently and accurately. This solution uses the Configurable Logic Block (CLB) peripheral and the SPI peripheral, eliminating the need for external hardware or complex software routines, ensuring seamless and reliable operation while minimizing Central Processing Unit (CPU) overhead.
Requirements
- CLB peripheral
- SPI peripheral
- WS2812/NeoPixel® array
- Find a Part - Microcontroller and Processor Products page
Block Diagrams
SPI to WS2812 Block Diagram
Figure 1 illustrates the main components of the SPI-to-WS2812 converter. The Serial Clock (SCK) pin of the SPI serves two purposes, enabling the counter and clocking the D latch for the Serial Data Out (SDO) input. The counter increments from zero to seven, resetting on the positive edge of the SCK signal.
The outputs from the counter and the D latch feed into a Look-Up Table (LUT). The LUT generates timing signals that replicate the WS2812 protocol. Specifically, the LUT outputs a sequence corresponding to a WS2812 "0" when D = 0 and a WS2812 "1" when D = 1. (Refer to Figure 2 for details.)
SPI to WS2812 Timing Diagram
Procedure
Implement the CLB Logic
Configure the CLB to implement the SPI to WS2812 logic, including the counter logic. Refer to Figure 1 for guidance. Refer to these tips and tricks for guidance on creating a module for the CLB or to download and import the counter as a library.
Select a Clock Source for the CLB
Set the CLB to use HFINTOSC with a Clock Divider of 4.
Configure SPI as a host with the following configuration:
- Requested Speed: 800kHz
- Mode 1
- Data Input Sampled at: Middle
Assign the SPI SDO pin as the data input and the SPI SCK pin as the clock input to the logic block. Then, assign the output from the logic block to the pin connected to the WS2812 data line.
Results
When successful, the LED display will alternate between all green and all red displays.
Learn More
- SPI to WS2812 — Use Case for CLB Using the PIC16F13145 Microcontroller with MCC Melody
- Configurable Logic Block (CLB)
- MPLAB Discover - More CLB Examples
- Configurable Logic Block (CLB) Traffic Light Demo
- How to Import External Libraries into Configurable Logic Block Synthesizer Tool
- How to Create a Module in the Configurable Logic Block (CLB) Synthesizer Tool