Referência de Pixel FastLED - FastLED Wiki GitHub
Referência de Pixel FastLED - FastLED Wiki GitHub
FastLED / FastLED
Code Issues 173 Pull requests 22 Actions Projects Wiki Security Insights
Pixel reference
Jump to bottom
Overview
There's two main pixel types in the library - the CRGB class and the CHSV class. CHSV objects
have to be converted to CRGB objects before they can be written out. You can also write CHSV
objects into the CRGB array and have the translation occur as necessary.
CRGB Reference
CHSV Object Reference
Predefined Colors Reference
CRGB Reference
<wiki:toc max_depth="3" />
Typically, when using this library, each LED strip is represented as an array of CRGB colors, one
color for each LED pixel.
For more general information on what the RGB color space is, see
http://en.wikipedia.org/wiki/RGB_color_model
https://github.com/FastLED/FastLED/wiki/Pixel-reference 1/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
Data Members
CRGB has three one-byte data members, each representing one of the three red, green, and blue
color channels of the color. There is more than one way to access the RGB data; each of these
following examples does exactly the same thing:
// The three color channel values can be referred to as "red", "green", and "blue"...
leds[i].red = 50;
leds[i].green = 100;
leds[i].blue = 150;
Direct Access
You are welcome, and invited, to directly access the underlying memory of this object if that suits
your needs. That is to say, there is no "CRGB::setRed( myRedValue )" method; instead you just
directly store 'myRedValue' into the ".red" data member on the object. All of the methods on the
CRGB class expect this, and will continue to operate normally. This is a bit unusual for a C++
class, but in a microcontroller environment this can be critical to maintain performance.
The CRGB object "is trivially copyable", meaning that it can be copied from one place in memory
to another and still function normally.
Methods
In addition to simply providing data storage for the RGB colors of each LED pixel, the CRGB class
also provides several useful methods color-manipulation, some of which are implemented in
assembly language for speed and compactness. Often using the class methods described here is
faster and smaller than hand-written C/C++ code to achieve the same thing.
https://github.com/FastLED/FastLED/wiki/Pixel-reference 2/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
CRGB colors can be set by assigning values to the individual red, green, and blue channels. In
addition, CRGB colors can be set a number of other ways which are often more convenient and
compact. The two pieces of code below perform the exact same function.
//Example 1: set color from red, green, and blue components individually
leds[i].red = 50;
leds[i].green = 100;
leds[i].blue = 150;
//Example 2: set color from red, green, and blue components all at once
leds[i] = CRGB( 50, 100, 150);
Some performance-minded programmers may be concerned that using the 'high level', 'object-
oriented' code in the second example comes with a penalty in speed or code size. However, this
is simply not the case; the examples above generate literally identical machine code, taking up
exactly the same amount of program memory, and executing in exactly the same amount of
time. Given that, the choice of which way to write the code, then, is entirely a matter of personal
taste and style. All other things being equal, the simpler, higher-level, more object-oriented code
is generally recommended.
Here are the other high-level ways to set a CRGB color in one step:
Again, for the performance-minded programmer, it's worth noting that all of the examples above
compile down into exactly the same number of machine instructions. Choose the method that
makes your code the simplest, most clear, and easiest to read and modify.
If you are copying a large number of colors from one (part of an) array to another, the standard
library function memmove can be used to perform a bulk transfer; the CRGB object "is trivially
copyable".
https://github.com/FastLED/FastLED/wiki/Pixel-reference 3/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
Introduction to HSV
CRGB color objects use separate red, green, and blue channels internally to represent each
composite color, as this is exactly the same way that multicolor LEDs do it: they have one red
LED, one green LED, and one blue LED in each 'pixel'. By mixing different amounts of red, green,
and blue, thousands or millions of resultant colors can be displayed.
However, working with raw RGB values in your code can be awkward in some cases. For example,
it is difficult to work express different tints and shades of a single color using just RGB values,
and it can be particular daunting to describe a 'color wash' in RGB that cycles around a rainbow
of hues while keeping a constant brightness.
To simplify working with color in these ways, the library provides access to an alternate color
model based on three different axes: Hue, Saturation, and Value (or 'Brightness'). For a complete
discussion of HSV color, see http://en.wikipedia.org/wiki/HSL_and_HSV , but briefly:
In the library, the "hue" angle is represented as a one-byte value ranging from 0-255. It runs
from red to orange, to yellow, to green, to aqua, to blue, to purple, to pink, and back to red. Here
are the eight cardinal points of the hue cycle in the library, and their corresponding hue angle.
https://github.com/FastLED/FastLED/wiki/Pixel-reference 4/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
Often in other HSV color spaces, hue is represented as an angle from 0-360 degrees. But for
compactness, efficiency, and speed, this library represents hue as a single-byte number from 0-
255. There's a full wiki page how FastLED deals with HSV colors here.
"saturation" is a one-byte value ranging from 0-255, where 255 means "completely saturated,
pure color", 128 means "half-saturated, a light, pale color", and 0 means "completely de-
saturated: plain white".
"valor" é um valor de um byte que varia de 0 a 255, representando brilho, onde 255 significa
"completamente brilhante, totalmente iluminado", 128 significa "um pouco esmaecido, apenas
meio iluminado" e zero significa "completamente escuro: preto".
O objeto CHSV
Na biblioteca, um objeto CHSV é usado para representar uma cor no espaço de cores HSV. O
objeto CHSV possui os três membros de dados de um byte que você pode esperar:
https://github.com/FastLED/FastLED/wiki/Pixel-reference 5/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
// Now...
// paleBlue.hue == 160
// paleBlue.sat == 128
// paleBlue.val == 255
Por exemplo, para definir um led para uma cor especificada no HSV, você pode simplesmente
atribuir uma cor CHSV a uma cor CRGB:
// alternate syntax
leds[i].setHSV( 160, 255, 255);
Não há conversão de CRGB para CHSV fornecida com a biblioteca neste momento.
Os "espectros" quase não têm amarelo real; a faixa amarela é incrivelmente estreita.
Os "arco-íris" têm uma faixa amarela aproximadamente da largura das faixas 'laranja' e
'verde' ao redor; a faixa amarela é fácil de ver.
Todas as conversões automáticas de cores na biblioteca usam o espaço de cores "HSV Rainbow",
mas através do uso de rotinas explícitas de conversão de cores, você pode optar por usar o
espaço de cores "HSV Spectrum". Há uma página wiki completa de como o FastLED lida com
cores HSV aqui .
https://github.com/FastLED/FastLED/wiki/Pixel-reference 6/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
O espaço de cores do HSV Spectrum possui diferentes pontos cardeais, e apenas seis deles, que
são correspondentemente distribuídos mais numericamente. Aqui está o mapa de cores
"Spectrum" que o FastLED fornece se você chamar hsv2rgb_spectrum explicitamente:
Vermelho (0 ..)
Amarelo (42 ..)
Verde (85 ..)
Aqua (128 ..)
Azul (171 ..)
Roxo (213 ..)
Por que usar o espaço de cores Spectrum, em vez de Rainbow? O espaço de cores do HSV
Spectrum pode ser convertido em RGB um pouco mais rápido do que o espaço de cores do HSV
Rainbow - mas os resultados não são tão bons visualmente; o pouco amarelo que aparece
parece sombrio e, com brilhos mais baixos, quase acastanhado. Portanto, há uma troca entre
alguns ciclos de relógio e a qualidade visual. Em geral, comece com as funções Rainbow (ou,
melhor ainda, com as conversões automáticas), e desça para as funções Spectrum somente se
você ficar completamente sem velocidade.
https://github.com/FastLED/FastLED/wiki/Pixel-reference 7/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
As duas funções de conversão do espaço de cores também podem converter uma matriz de
cores CHSV em uma matriz correspondente de cores CRGB:
A função "hsv2rgb_spectrum" também pode ser chamada dessa maneira para conversões em
massa.
Comparando cores
As cores do CRGB podem ser comparadas para correspondências exatas usando == e! =.
As cores do CRGB podem ser comparadas para níveis de luz relativos usando <,>, <= e =>.
Observe que esta é uma comparação numérica simples e nem sempre corresponde ao brilho
percebido das cores.
Muitas vezes, é útil verificar se uma cor é completamente "preta" ou se está "acesa". Você pode
fazer isso testando a cor diretamente com 'if' ou usando-a em qualquer outro contexto
booleano.
Color Math
A biblioteca suporta um rico conjunto de operações de 'matemática de cores' que você pode
executar em uma ou mais cores. Por exemplo, se você quiser adicionar um pouco de vermelho a
uma cor de LED existente, faça o seguinte:
// Here's all that's needed to add "a little red" to an existing LED color:
leds[i] += CRGB( 20, 0, 0);
É isso aí.
https://github.com/FastLED/FastLED/wiki/Pixel-reference 8/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
Se você já fez esse tipo de coisa manualmente, pode notar que falta algo: a verificação do canal
vermelho transbordando além das 255. Tradicionalmente, você provavelmente já teve que fazer
algo assim:
Esse tipo de lógica de adicionar e verificar e ajustar se necessário é resolvida dentro do código
da biblioteca para adicionar duas cores CRGB, dentro do operador + e operador + =. Além disso,
grande parte dessa lógica é implementada diretamente na linguagem assembly e é
substancialmente menor e mais rápida que o código C / C ++ correspondente. O resultado
líquido é que você não precisa mais fazer todas as verificações e seu programa também é
executado mais rapidamente.
Essas operações de 'matemática da cor' fazem parte do que torna a biblioteca rápida: permite
desenvolver seu código mais rapidamente, além de executá-lo mais rapidamente.
Todas as operações matemáticas definidas nas cores do CRGB são automaticamente protegidas
contra quebra, estouros e subfluxo.
// Subtract a constant "1" from the brightness of all three (RGB) channels.
leds[i]--;
https://github.com/FastLED/FastLED/wiki/Pixel-reference 9/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
Existem dois métodos diferentes para escurecer uma cor: estilo "vídeo" e estilo "matemática
bruta". O estilo de vídeo é o padrão e é explicitamente projetado para nunca diminuir
acidentalmente nenhum dos canais RGB de um LED aceso (não importa o quão escuro) para um
LED aceso - porque isso geralmente parece errado com baixos níveis de brilho. O estilo
"matemática bruta" acabará por ficar preto.
As cores são sempre esmaecidas por uma fração. A fração de escurecimento é expressa em 256º,
portanto, se você deseja diminuir uma cor em 25% do brilho atual, primeiro é necessário
expressá-lo em 256º. Nesse caso, 25% = 64/256.
Você também pode expressar isso da outra maneira: deseja diminuir o pixel para 75% do brilho
atual. 75% = 192/256. Existem duas maneiras de escrever isso, e ambas farão a mesma coisa. O
primeiro usa o operador% =; a lógica aqui é que você está definindo a nova cor como "uma
porcentagem" do valor anterior:
Se você deseja que a cor desapareça até o preto, use uma destas funções:
Também é fornecida uma função para aumentar uma determinada cor até o brilho máximo,
mantendo o mesmo tom:
https://github.com/FastLED/FastLED/wiki/Pixel-reference 10/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
Finalmente, as cores também podem ser ampliadas ou reduzidas usando multiplicação e divisão.
A biblioteca também fornece funções para procurar o brilho aparente (ou matemático) de uma
cor.
https://github.com/FastLED/FastLED/wiki/Pixel-reference 11/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 12/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 13/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 14/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 15/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 16/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 17/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 18/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 19/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 20/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 21/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 22/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 23/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 24/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 25/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 26/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 27/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 28/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
https://github.com/FastLED/FastLED/wiki/Pixel-reference 29/30
27/06/2020 Referência de pixel · FastLED / FastLED Wiki · GitHub
Páginas 28.
Documentação
perguntas frequentes
Visão geral
LEDs de fiação
Uso básico
LEDs de controle
Referência de Pixel
Referência RGBSet
Cores FastLED HSV
Matemática de Alto Desempenho
Notas de poder
Funções de onda FastLED
Limitações da plataforma
Problemas de interrupção
Notas ESP8266
Saída paralela
Referências
Design FastLED
Correção de cores FastLED
Pontilhamento Temporal FastLED
Hardware SPI ou Batida de bits
Exemplos
Calibração RGB
Exemplos de controladores múltiplos
Melhor das discussões do FastLED
Referência da API
Referência de chipset
Novos recursos do FastLED3.1
Lançamentos
Anúncio FastLED-3.0 - página de lançamento 3.0
https://github.com/FastLED/FastLED.wiki.git
https://github.com/FastLED/FastLED/wiki/Pixel-reference 30/30