# Lighting (Squared)

*Special thanks to Dr. Shawn Chiappetta from the University of Sioux Falls for grinding the rust off my math skills.*

Controlling the lights was the most basic, and first thing reefin.net needed to do, and it does that pretty well. Currently it goes through a series of 6 “phases” and uses a crude fadeTo method I wrote so as to make it look okay while it’s fading up. It works well enough that I don’t really notice it happening while it’s on the desk next to me.

But that’s not good enough!

What I really want is a bit more dynamic: something that can load a quintic polynomial curve (5 degrees) which represents desired power on the Y axis, and the time (0 -> 24 hours) on the X axis. We’ll calculate Y by telling it X based on the current time. One such example of that looks like this:

y = -0.0028 * X^5 + 0.4571 * x^4 – 17.817 * x^3 + 238.83 * x^2 – 874.71 * x + 266.29

Now that we’ve got our equation, lets break down some code!

Here we the 5 values from our polynomial equation:

double[] day1 = new double[] { -0.0028, 0.4571, -17.817, 238.83, -874.71, 266.29 };

We’ll create a value to hold our power and set it to the 5th term:

double CurrentPower = day1[5];

Now we’ll figure out the date and time in decimal form to use as x in our equation:

double calcTime = DateTime.Now.Hour; // hours in 24 hour format calcTime += (((double)(DateTime.Now.Minute) / 60)); // convert minutes to fractional hours

Now (with order of operations in mind) we can evaluate exponents of our date/time and multiply them by our other terms:

CurrentPower += day1[4] * calcTime; CurrentPower += day1[3] * System.Math.Pow(calcTime, 2); CurrentPower += day1[2] * System.Math.Pow(calcTime, 3); CurrentPower += day1[1] * System.Math.Pow(calcTime, 4); CurrentPower += day1[0] * System.Math.Pow(calcTime, 5);

Finally, because my curve starts below zero (and other curves might start earlier or later in the day) we’ll make anything negative just be zero:

if (CurrentPower < 0) CurrentPower = 0;

And finally, we’ll need to round to a whole number to make this work. I will round with a cast to int, which is the format I need it in anyway:

int SetPower = (int)(CurrentPower);

Now I can set my power of the light to the “SetPower” variable, either scale the value, or repeat for each other channel and that’s it! We’ve taken a curve and grabbed what power should be at the given moment. Loop this every so often (I’m thinking 1-2 seconds) and presto! Constant fade of lights.