Linear Interpolation > RGB Colour Switching <Code Snippet>

331 views
Skip to first unread message

benmatthew

unread,
Oct 13, 2009, 6:51:46 AM10/13/09
to DmxSimple
I thought I'd post my code snippet for Linear Interpolation. Which
basically does switching between RGB values. There's probably a more
efficient way of doing it, but I thought I might as well share. If
anyone has any ways to improve this code I'm more than welcome to hear
it.

More info on the basics of Linear Interpolation can be found:
http://tech-algorithm.com/articles/linear-interpolation/

Thanks again Peter for the DMX library and for suggesting doing Linear
Interpolation. Turns out I'd actually learnt it in class in my first
year of CS.



void loop() {
int brightness=90;
int rgbDelay=50;

linearInterpolationRGB(255,0,0, 0,0,255, 255,rgbDelay,
brightness); //Start RGB values 255,0,0 end values 0,255
linearInterpolationRGB(0,0,255, 0,255,0, 255,rgbDelay,
brightness);
linearInterpolationRGB(0,255,0, 255,255,255, 255,rgbDelay,
brightness);
linearInterpolationRGB(255,255,255, 255,0,0, 255,rgbDelay,
brightness);

}



void linearInterpolationRGB(int r0, int g0, int b0, int r1, int g1,
int b1, int tLength, int d, int b) {

//r0, g0, b0 Represents current RGB value
//r1, g1, b1 Destination RGB value
//tlength the total transition length
//d => delay inbetween switching each colours (longer delay, longer
time to switch)
//b => set brightness


int newRed;
int newGreen;
int newBlue;
int currentPos;

for (int i=0; i <= tLength; i++){
//RED
newRed=r0+((i*(r1-r0))/tLength);
//Green
newGreen=g0+((i*(g1-g0))/tLength);
//Blue
newBlue=b0+((i*(b1-b0))/tLength);
Serial.println("Red");
Serial.println(newRed);
Serial.println("Green");
Serial.println(newGreen);
Serial.println("Blue");
Serial.println(newBlue);
Serial.println("i");
Serial.println(i);

DmxSimple.write(1,newRed);
DmxSimple.write(2,newGreen);
DmxSimple.write(3,newBlue);
DmxSimple.write(4,b);

delay(d);

}
}
Reply all
Reply to author
Forward
0 new messages