unsignedlongcurrentMicros=micros();// Get the current time
val[0]=valR;
val[1]=valG;
val[2]=valB;
for(inti=0;i<3;i++)
{
if(previousVal[i]!=val[i])// Only calculate the ON and OFF time if the value has changed
{
onTime[i]=(period*(unsignedlong)val[i])/255UL;// Not sure if that much variable type casting is necessary, but it works
offTime[i]=period-onTime[i];
previousVal[i]=val[i];
}
if(state[i]==LOW&¤tMicros-previousMicros[i]>=offTime[i]&&offTime[i]!=period)// If the LED is OFF AND we exceeded the OFF time AND the OFF time isn't equal to the period, turn the LED ON
{
state[i]=HIGH;
previousMicros[i]=currentMicros;
}
elseif(state[i]==HIGH&¤tMicros-previousMicros[i]>=onTime[i]&&onTime[i]!=period)// Else, if the LED is ON AND we exceeded the ON time AND the ON time isn't equal to the period, turn the LED OFF