
WS2812B addressable LEDs need a single data line with precise timing, which makes them a good test of how well a microcontroller can produce exact waveforms. In this guide, we drive a 24-LED WS2812B string from an STM32F411 by using the SPI peripheral as a precise pulse generator instead of toggling a GPIO pin in software.
In this guide, we shall cover the following:
- Introduction.
- STM32CubeMX setup.
- Hardware setup.
- Importing the project to STM32CubeIDE
- Firmware development.
- Results.
1. Introduction:
WS2812B addressable LEDs are popular because they are easy to wire. Each LED combines red, green and blue emitters and a small controller in one 5050 package. A whole chain of them, whether a strip, a matrix or a ring like the 24-LED ring in this guide, needs only three wires: 5 V, ground and one data line. Every LED in the chain can show its own colour at 256 brightness levels per channel. That makes the WS2812B a common choice for status indicators, decorative lighting, displays and user feedback in embedded products.
The same single wire is what makes the WS2812B hard to drive. Interfaces like SPI and I²C have a separate clock line that tells the receiver when to sample each bit. The WS2812B has none. It works out each bit from how long the data line stays high.
- Bit timing: A bit starts with a rising edge. A short high pulse of about 0.4 µs is a 0, and a long high pulse of about 0.8 µs is a 1. The line then stays low for the rest of the bit period, about 1.25 µs in total, which gives an 800 kbit/s data rate. The datasheet allows only about ±150 ns of error on these pulses.
- Data order: Each LED takes 24 bits, in green-red-blue order with the most significant bit first. It keeps the first 24 bits it receives and passes everything after them to the next LED.
- Latch: When the line stays low longer than the reset time (tens of microseconds, and longer on newer parts), every LED shows the colour it just received.
In practice, the timing tolerance is roughly the length of a few dozen CPU cycles, and it applies to every bit of every LED in the chain.
Bit-banging
The obvious way to produce this waveform is to bit-bang it: write a loop that sets a GPIO pin high, waits, sets it low, waits again, and repeats for each of the 24 bits per LED. On paper this is simple. In practice, it has several problems:
- The timing comes from instruction counts. At the 80 MHz system clock used in this project, 0.4 µs is only 32 CPU cycles. The delay has to be tuned to the exact instructions the compiler generates. Changing the optimisation level, the system clock, the flash wait states, or even a nearby line of code can move the pulse edges outside the tolerance. These failures often look random: a wrong colour on one LED, a flicker, or a ring that works in a Debug build and fails in Release.
- Interrupts corrupt the data. If SysTick, a UART receive or a timer update interrupts the loop in the middle of a bit, the high pulse stretches. A 0 can turn into a 1, and every LED after that point in the chain gets wrong data. The usual fix is to disable interrupts for the whole frame. For a long string, that can block the system for milliseconds, causing missed bytes, delayed control loops and late timeouts.
- The CPU is fully busy. While the frame is being sent, the core does nothing but toggle a pin and count cycles. The time grows with the number of LEDs, and none of it is available for the application.
- It does not port well. A delay loop tuned for one microcontroller at one clock speed is rarely correct on another. Every new target, clock change or compiler update means checking the waveform on a logic analyser again.
Using SPI
A better approach is to let a hardware peripheral handle the timing. The SPI peripheral on the STM32F411 is a good fit, even though the WS2812B is not an SPI device. An SPI master shifts bits out of its MOSI pin at a fixed rate set by its clock prescaler. If you choose the byte pattern that goes into the SPI data register, the MOSI line produces whatever pulse shape you need, with edges as precise as the peripheral clock.
This project runs SPI1 from the 80 MHz APB2 clock with a prescaler of 32. That gives 2.5 Mbit/s, so each SPI bit lasts exactly 400 ns. That is the WS2812B’s short pulse, and two SPI bits make the long pulse. Each WS2812B bit is sent as one SPI byte:
- A 1 is
0b110(00000110), which produces an 800 ns high pulse. - A 0 is
0b100(00000100), which produces a 400 ns high pulse.
The rest of each byte is low. The WS2812B mainly looks at the width of the high pulse, and this low time stays well below the reset threshold, so the LEDs read the stream correctly. Each LED’s 24 colour bits become 24 SPI bytes, and the driver sends them out on MOSI (PA7). SPI1 is set to transmit-only, so SCK is configured but stays unconnected because the LEDs do not need a clock.
The benefits follow from that:
- Hardware-defined timing: The pulse widths come from the peripheral clock, not from instruction counts. Compiler settings and code changes no longer affect them.
- Interrupt tolerance: An interrupt can delay the CPU from loading the next byte, but it cannot change the width of a pulse that is already being shifted out. A short delay between bytes only adds low time, which the LEDs tolerate.
- Portability: Moving to another clock speed or microcontroller means picking a new prescaler and checking that each SPI bit is still 400 ns. There are no delay loops to retune.
- A path to DMA: The frame is now a plain byte buffer, so it is easy to move from the blocking
HAL_SPI_Transmitused here to DMA. The CPU then only prepares the buffer and starts the transfer, and the frame goes out with no CPU involvement.
2. STM32CubeMX Setup:
Open STM32CubeMX as start a new project as follows:

Search for your STM32 MCU, select the MCU and click on Start New Project as follows:

From System Configuration, select RCC and enable the High Speed Clock (HSI):
- For Nucleo based board, select bypass.
- For a connected crystal, select crystal/ceramic resonator.

Next, from Clock Configuration, set the core frequency to 80MHz as follows:
Since the Nucleo has 8MHz clock source, the input frequency has been set to

Next, from connectivity, select SPI and configure it as follows:
- Set the mode to half duplex master
- Set the prescaller to 32, this will generate the required pulse length

According to the datasheet of the WS2812, a bit is considered as 0 if the signal remains HIGH for 0.35us and LOW for 0.8us. And for a bit to be considered as a 1, the signal remains HIGH for 0.7us and LOW for 0.6us. Of course this is flexible with an error up to ±150ns.
Also the reset signal is supplied by pulling the data line low for more than 50us.

We will use 3 SPI bits to represent a single bit for the WS2812. The 3 SPI bits will have the time period of 1.2us (0.4*3).

Next, from Project Manager tab, Code Generation tab, check Generate peripheral initialization as pair of .c/.h files for each peripheral.

Next, from Project tab, set the toolchain/IDE to STM32CubeIDE, give the project a name and click on generate code.

Thats all for the STM32CubeMX setup.
3. Hardware Setup:
The connection as following:

Simply, connect the data pin of WS2812B to PA7 or MOSI pin of the STM32 MCU.
4. Importing the Project to STM32CubeIDE:
Open STM32CubeIDE, select your workspace and click on Launch.
From the IDE, click File and select STM32 Project Create/Import as follows:

Next, from Import STM32 Project, select STM32CubeMX/STM32CubeIDE Project and click on Next as follows:

Next, select the folder that contains the .ioc file and click on Finish as follows:

Note: Project name is for reference only.
5. Firmware Development:
Before we start with the development, here is the flowchart for the sending data over the SPI:

We start by creating new source and header file with name of ws2812b.c and ws2812b.h respectively.
Open ws2812b header file.
Within the header file, we start by including the following header files:
- main.h
- spi.h
- stdint.h
as follows:
#include "stdint.h" #include "main.h" #include "spi.h"
Next, declare how many LEDs do you have:
#define NUM_OF_LEDs 24
Next, the brightness level to be set:
void WS2812_Set_Brightness(uint8_t value);
Next, set the RGB values for the desired LED:
void WS2812_Set_LED_Color (int led, int RED, int GREEN, int BLUE);
Finally, set the LED:
void WS2812_Set (void);
Hence, the header file:
#ifndef WS2812_H_ #define WS2812_H_ #include "stdint.h" #include "main.h" #include "spi.h" /*Set number of LED in the string*/ #define NUM_OF_LEDs 24 /* * @brief This function will set the LED Brightness. * @param brightness value. * @return nothing. * */ void WS2812_Set_Brightness(uint8_t value); /* * @brief This function will set the LED colors value. * @param led: LED Number. * @param RED: Red color value. * @param GREEN: Green color value. * @param BLUE: Blue color value. * @retun nothing * */ void WS2812_Set_LED_Color (int led, int RED, int GREEN, int BLUE); /* * @brief This function will write the data to the LED string. * @param nothing. * @return nothing * */ void WS2812_Set (void); #endif /* WS2812_H_ */
Next, open ws2812b source file.
We start by including the ws2812b header file as follows:
#include "WS2812.h"
Next, variable to hold the brightness value, by default, set to 100:
uint8_t brightness=100;
2 dimensions array to hold the data of the LED:
uint8_t LED_Data[NUM_OF_LEDs][4];
Next, for brightness level for the LED:
void WS2812_Set_Brightness(uint8_t value)
{
if(value>100)value=100;
brightness=value;
}Next, the function to set the LED color:
void WS2812_Set_LED_Color (int led, int RED, int GREEN, int BLUE)
{
LED_Data[led][0] = led;
LED_Data[led][1] = GREEN;
LED_Data[led][2] = RED;
LED_Data[led][3] = BLUE;
}Next, the function to send SPI data to the LED:
static void ws2812_spi (int GREEN, int RED, int BLUE)
{
GREEN = GREEN*brightness/100;
RED = RED*brightness/100;
BLUE = BLUE*brightness/100;
uint32_t color = GREEN<<16 | RED<<8 | BLUE;
uint8_t sendData[24];
int indx = 0;
for (int i=23; i>=0; i--)
{
if (((color>>i)&0x01) == 1) sendData[indx++] = 0b110; // store 1
else sendData[indx++] = 0b100; // store 0
}
HAL_SPI_Transmit(&hspi1, sendData, 24, 100);
}Finally, the set function:
void WS2812_Set (void)
{
for (int i=0; i<NUM_OF_LEDs; i++)
{
ws2812_spi(LED_Data[i][1], LED_Data[i][2], LED_Data[i][3]);
}
HAL_Delay(1);
}Hence, the entire source file:
#include "WS2812.h"
uint8_t brightness=100;
uint8_t LED_Data[NUM_OF_LEDs][4];
void WS2812_Set_Brightness(uint8_t value)
{
if(value>100)value=100;
brightness=value;
}
void WS2812_Set_LED_Color (int led, int RED, int GREEN, int BLUE)
{
LED_Data[led][0] = led;
LED_Data[led][1] = GREEN;
LED_Data[led][2] = RED;
LED_Data[led][3] = BLUE;
}
static void ws2812_spi (int GREEN, int RED, int BLUE)
{
GREEN = GREEN*brightness/100;
RED = RED*brightness/100;
BLUE = BLUE*brightness/100;
uint32_t color = GREEN<<16 | RED<<8 | BLUE;
uint8_t sendData[24];
int indx = 0;
for (int i=23; i>=0; i--)
{
if (((color>>i)&0x01) == 1) sendData[indx++] = 0b110; // store 1
else sendData[indx++] = 0b100; // store 0
}
HAL_SPI_Transmit(&hspi1, sendData, 24, 100);
}
void WS2812_Set (void)
{
for (int i=0; i<NUM_OF_LEDs; i++)
{
ws2812_spi(LED_Data[i][1], LED_Data[i][2], LED_Data[i][3]);
}
HAL_Delay(1);
}
Next, open main.c file.
In user code includes begin, include the following head files:
#include "stdlib.h" #include "WS2812.h"
The stdlib is used to get the random function.
Next, in user code begin 2 in main function:
srand(HAL_GetTick()); WS2812_Set_Brightness(100);
seed the random function and set the led brightness to 100.
In user code begin 3 in while 1 loop:
We shall set each LED to has a random color and go back and forth.
for (int i=0;i<NUM_OF_LEDs;i++)
{
srand(HAL_GetTick());
WS2812_Set_LED_Color(i,random()%256,random()%256,random()%256);
WS2812_Set();
HAL_Delay(random()%100);
}
HAL_Delay(200);
for (int i=NUM_OF_LEDs;i>=0;i--)
{
srand(HAL_GetTick());
WS2812_Set_LED_Color(i,0,0,0);
WS2812_Set();
HAL_Delay(random()%100);
}
HAL_Delay(200);Thats all for the firmware.
Save, build the project and run it as follows:

You may download the project from our github repository from here.
6. Results:
You should get the following:
Thats all for the guide.
Happy coding 😉


Discussion