dac教學 - c++淡入淡出顏色?(Arduino的)
arduino類比腳位不夠 (2)
不可能褪色,因為你是從紅色開始,以綠色結束。
為了避免這種錯誤,我建議你寫一個面向對象的代碼。
如果您不想編寫類來處理3D vectonr,則可以使用Arduino Tinker Library
我為你寫了這個例子:
#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);
}
在串口上打印下面的輸出
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]
希望這有助於:)
https://src-bin.com
我目前有這樣的2套顏色之間的褪色:
for(int i=0;i<nLEDs;i++){
a = (255 / 100) * (incomingByte * sensitivity);
r = (r * 7 + a + 7) / 8;
g = (g * 7 + (255 - a) + 7) / 8;
b = 0;
FTLEDColour col = { r , g , b };
led.setLED(i, col);
}
但現在我試圖讓用戶輸入自己的顏色:
// > Colour fade, Start colour
int colFade1Red = 0;
int colFade1Green = 255;
int colFade1Blue = 0;
// > Colour fade, End colour
int colFade2Red = 255;
int colFade2Green = 0;
int colFade2Blue = 0;
int fadeAm = 7; // Fade speed
隨著衰落的代碼:
void ColourFade(){
for(int i=0;i<nLEDs;i++){
r = ctest(colFade1Red, colFade2Red, r);
g = ctest(colFade1Green, colFade2Green, g);
b = ctest(colFade1Blue, colFade2Blue, b);
FTLEDColour col = { r , g , b };
led.setLED(i, col);
}
}
int ctest(int col1, int col2, int cur){
int temp = col1 - col2;
if(temp < 0) { temp = -temp; }
int alp = (temp / 100) * (incomingByte * sensitivity);
if(col1 < col2){
return (cur * fadeAm + (col2 - alp) + fadeAm) / (fadeAm +1 );
} else {
return (cur * fadeAm + alp + fadeAm) / (fadeAm +1 );
}
}
但是,這從第二個用戶顏色開始,並淡化成粉紅色。 我將如何正確淡入顏色?
另外“incomingByte”是一個介於0和100之間的值,代碼位於更新循環中。
Answer #1
顏色之間的平滑過渡最好在不同的顏色空間中完成(恕我直言)。
例如,要從亮紅色轉換為亮綠色,是否要通過明亮的黃色(在色輪邊緣附近)或通過#808000(暗黃色) - 這是直線插值會給你的內容RGB域。
為了我的Moodlamp應用程序 ,我使用了HSL顏色空間。 我指定了開始顏色和結束顏色,以及一些轉換步驟。 這使我能夠計算在過渡的每個點上H,S和L的調整量。
只有在使用顏色的時候,我才轉換回RGB。
你可以在這裡看到javascript代碼(請記住這是我寫的第一個Javascript代碼,所以如果它看起來不是非慣用的,那可能是為什麼!):
https://github.com/martinjthompson/MoodLamp/blob/master/app/assistants/lamp-assistant.js