How to Drive WS2812 LEDs (SPI-to-WS2812)

Last modified by Microchip on 2025/01/02 09:53

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

Block Diagrams

SPI to WS2812 Block Diagram

SPI to WS2812 Block Diagram Using MPLAB Melody

Figure 1

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

SPI to WS2812 Timing Diagram

Figure 2

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.

Information

Note: If using MPLAB® Code Configurator, use the CLB Synthesizer tool or download the pre-configured CLB file.

Back to Top


Select a Clock Source for the CLB

Set the CLB to use HFINTOSC with a Clock Divider of 4.

Back to Top


Configure SPI as a host with the following configuration:

  • Requested Speed: 800kHz
  • Mode 1
  • Data Input Sampled at: Middle

Back to Top


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.

Back to Top

Results

When successful, the LED display will alternate between all green and all red displays. 

WS2812 LED Display Driven By CLB and SPI Peripherals

Back to Top

Learn More

Back to Top