// "Ziggurat Mood Light" // Lee Felarca // 2010-10-01 // v0.9b #define LED_G1 11 #define LED_G2 10 #define LED_B1 9 #define LED_B2 5 #define SENSOR 0 // The range of values that the sensor responds to. // Use to calibrate to specific ambient light conditions int sensorMin = 20; int sensorMax = 90; // The maximum brightness of the LED's. // Can be set lower if too bright... int ledMax = 255; // Value mapped to LED brightness float scalarTo = 1.0; int debugCount; int count; // void setup() { Serial.begin(9600); pinMode(LED_G1, OUTPUT); pinMode(LED_G2, OUTPUT); pinMode(LED_B1, OUTPUT); pinMode(LED_B2, OUTPUT); } void loop() { // Get light sensor value int i = analogRead(SENSOR); float scalar = (float)(i - sensorMin) / (float)(sensorMax - sensorMin) ; if (scalar < 0) scalar = 0; if (scalar > 1) scalar = 1; // clamp to range of [0,1] if (scalar > scalarTo) { scalarTo += (scalarTo > 0.66) ? 0.0010 : 0.0040; } else if (scalar < scalarTo) { scalarTo -= (scalarTo > 0.66) ? 0.0010 : 0.0040; } if (abs(scalarTo - scalar) <= 0.0040) scalarTo = scalar; // Calculate LED brightness float out = (1.0 - scalarTo) * (1.0 - scalarTo); // (convert from linear to exponential) float b = out * (float)ledMax; int bInt = floor(b); // base brightness value, range of [0,255] // Modify base brightness value based on sine wave to continually // crossfade between green and blue count++; float bias = sin(count * (PI/(180*10))); // ... sine wave period = 180 * 10 * 10ms float gbias = (bias + 1.0) / 2.0; // [0,1] int green = (int)(bInt * gbias); float bbias = (bias*-1.0 + 1.0) / 2.0; // [0,1] int blue = (int)(bInt * bbias); analogWrite(LED_G1, green); analogWrite(LED_G2, green); analogWrite(LED_B1, blue); analogWrite(LED_B2, blue); // Debug output... debugCount++; if (debugCount % 100 == 0) { Serial.print("raw "); Serial.println(i); Serial.print("scalar "); Serial.println(scalar); Serial.print("scalarTo "); Serial.println(scalarTo); Serial.print("write "); Serial.println(b); } // Force loop to run at 100 hertz delay(10); }