Nicola Pezzotti

Research Scientist and Engineer in Machine Learning and Visual Analytics

Follow me on GitHub

Color fading with arduino

10 Dec 2013 Yesterday evening I encountered this question on StackOverflow website.


In my opinion, the low quality of the original code is the main problem here. I suggested Tristan to use the Arduino Tinker Library and I wrote an example just for him.

#include <Vect3d.h>
#include <SerialLog.h>

Tinker::Vect3d<float> red(255,0,0);
Tinker::Vect3d<float> green(0,255,0);
Tinker::SerialLog serialLog;

void setup(){
Serial.begin(9600);
serialLog
.display("Fade color example");
serialLog
.endline();
}

void loop(){
//fade factor computation
const uint32_t t = millis()%10000;
const float cosArg = t/10000.*3.1415*2;
const float fade = abs(cos(cosArg));

//Here's the color computation... as you can see is very easy to do!! :)
Tinker::Vect3d<uint8_t> finalColor(red*fade + green*(1-fade));

//We print the vect3d on the arduino serial port
Tinker::LOG::displayVect3d(finalColor,&serialLog);
serialLog
.endline();
delay
(500);
}
This example will print the following output on the serial port:
Fade color example
V
[255;0;0]
V
[242;12;0]
V
[206;48;0]
V
[149;105;0]
V
[78;176;0]
V
[0;254;0]
V
[79;175;0]
V
[150;104;0]
V
[206;48;0]
V
[242;12;0]
V
[254;0;0]
V
[242;12;0]
V
[205;49;0]
V
[148;106;0]
V
[77;177;0]
V
[1;253;0]
V
[80;174;0]
V
[151;103;0]

If you want to fade multiple colors in one of your sketch you can simply use this code! :)

PS: Today I found this question on stack overflow: http://stackoverflow.com/questions/20482642/how-to-fade-between-two-vectors-by-value.

I'm really proud that someone is using the Arduino Tinker Library :)