RGB fade using millis()

Hello everyone,

I am currently working on a rather simple project which includes a RGB LED which is supposed to fade at certain coordinates coming from a GPS module.

Although I'm not a routined programmer I managed to collect and merge two codes for reading the GPS data and fading the LED.
The only issue I have now (as far as I can tell) is that the delay in the fade code is interrupting the GPS data input. I read many threads concerning the same issue and methods regarding multithreading such as blinking led without delay but I just cannot get my head around how to implement the millis() function instead of the delay in this case.

This is the part of the code with the delay

void crossFade(int color[3]) {
  // Convert to 0-255
  int R = (color[0] * 255) / 100;
  int G = (color[1] * 255) / 100;
  int B = (color[2] * 255) / 100;

  int stepR = calculateStep(prevR, R);
  int stepG = calculateStep(prevG, G); 
  int stepB = calculateStep(prevB, B);

  for (int i = 0; i <= 1020; i++) {
    redVal = calculateVal(stepR, redVal, i);
    grnVal = calculateVal(stepG, grnVal, i);
    bluVal = calculateVal(stepB, bluVal, i);

    analogWrite(redPin, redVal);   // Write current values to LED pins
    analogWrite(grnPin, grnVal);      
    analogWrite(bluPin, bluVal); 

    delay(wait); // Pause for 'wait' milliseconds before resuming the loop
    }

It would be amazing if you could help me with this last step to (hopefully) solving my problem.

Here's the full code:

#include <SoftwareSerial.h>
#include <TinyGPS.h>

long lat,lon;     // create variable for latitude and longitude object
long lat2,lon2;   // copy of lat lon

// Output RGB LED
int redPin = 9;   // Red LED,   connected to digital pin 9
int grnPin = 10;  // Green LED, connected to digital pin 10
int bluPin = 11;  // Blue LED,  connected to digital pin 11

// Color arrays
int black[3]  = { 0, 0, 0 };
int dimPurple[3] = { 20, 0, 30 };

// Set initial color
int redVal = black[0];
int grnVal = black[1]; 
int bluVal = black[2];

int wait = 3;      // 10ms internal crossFade delay; increase for slower fades
int hold = 0;       // Optional hold when a color is complete, before the next crossFade
int repeat = 0;     // How many times should we loop before stopping? (0 for no stop)

// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;

SoftwareSerial gpsSerial(2,3); //create sensor connection
TinyGPS gps; // create GPS Object

void setup() {
  
  pinMode(redPin, OUTPUT);   // sets the pins as output
  pinMode(grnPin, OUTPUT);   
  pinMode(bluPin, OUTPUT); 

  lat2=lat;                  // copy variables
  lon2=lon;

  Serial.begin(9600); // connect serial
  gpsSerial.begin(9600); // connect gps sensor
 
}

void loop() {

  while(gpsSerial.available()){     // check for gps data
    if(gps.encode(gpsSerial.read())){ // encode gps data
    gps.get_position(&lat,&lon);    // get latitude and longitude

    // serial display position
    Serial.println("Position: ");
    Serial.print("lat ");Serial.print(lat);Serial.print(" lon ");Serial.println(lon);
    }
  }
    if( (lat <= 51456200 && lat2 >= 51456000) && (lon <= 5468950 && lon2 >= 5468600) ){
      crossFade (black);
      crossFade (dimPurple);
  }
}





/* BELOW THIS LINE IS THE MATH -- YOU SHOULDN'T NEED TO CHANGE THIS FOR THE BASICS
* 
* The program works like this:
* Imagine a crossfade that moves the red LED from 0-10, 
*   the green from 0-5, and the blue from 10 to 7, in
*   ten steps.
*   We'd want to count the 10 steps and increase or 
*   decrease color values in evenly stepped increments.
*   Imagine a + indicates raising a value by 1, and a -
*   equals lowering it. Our 10 step fade would look like:
* 
*   1 2 3 4 5 6 7 8 9 10
* R + + + + + + + + + +
* G   +   +   +   +   +
* B     -     -     -
* 
* The red rises from 0 to 10 in ten steps, the green from 
* 0-5 in 5 steps, and the blue falls from 10 to 7 in three steps.
* 
* In the real program, the color percentages are converted to 
* 0-255 values, and there are 1020 steps (255*4).
* 
* To figure out how big a step there should be between one up- or
* down-tick of one of the LED values, we call calculateStep(), 
* which calculates the absolute gap between the start and end values, 
* and then divides that gap by 1020 to determine the size of the step  
* between adjustments in the value.
*/

int calculateStep(int prevValue, int endValue) {
  int step = endValue - prevValue; // What's the overall gap?
  if (step) {                      // If its non-zero, 
    step = 1020/step;              //   divide by 1020
  } 
  return step;
}

/* The next function is calculateVal. When the loop value, i,
*  reaches the step size appropriate for one of the
*  colors, it increases or decreases the value of that color by 1. 
*  (R, G, and B are each calculated separately.)
*/

int calculateVal(int step, int val, int i) {

  if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
    if (step > 0) {              //   increment the value if step is positive...
      val += 1;           
    } 
    else if (step < 0) {         //   ...or decrement it if step is negative
      val -= 1;
    } 
  }
  // Defensive driving: make sure val stays in the range 0-255
  if (val > 255) {
    val = 255;
  } 
  else if (val < 0) {
    val = 0;
  }
  return val;
}

/* crossFade() converts the percentage colors to a 
*  0-255 range, then loops 1020 times, checking to see if  
*  the value needs to be updated each time, then writing
*  the color values to the correct pins.
*/

void crossFade(int color[3]) {
  // Convert to 0-255
  int R = (color[0] * 255) / 100;
  int G = (color[1] * 255) / 100;
  int B = (color[2] * 255) / 100;

  int stepR = calculateStep(prevR, R);
  int stepG = calculateStep(prevG, G); 
  int stepB = calculateStep(prevB, B);

  for (int i = 0; i <= 1020; i++) {
    redVal = calculateVal(stepR, redVal, i);
    grnVal = calculateVal(stepG, grnVal, i);
    bluVal = calculateVal(stepB, bluVal, i);

    analogWrite(redPin, redVal);   // Write current values to LED pins
    analogWrite(grnPin, grnVal);      
    analogWrite(bluPin, bluVal); 

    delay(wait); // Pause for 'wait' milliseconds before resuming the loop
    }
  
  // Update current values for next loop
  prevR = redVal; 
  prevG = grnVal; 
  prevB = bluVal;
  delay(hold);
}

Thanks a lot

You don't have to implement the millis() function!!

All time dependent stuff needs to be conditional on the value of millis() reaching an appropriate value,
all the conditional tests being checked each time through loop().

That way everything gets a look-in.

For your ramping:

  if (ramping && millis()-last_ramp_time >= wait)
  {
    last_ramp_time += wait ;
    redVal = calculateVal(stepR, redVal, i);
    grnVal = calculateVal(stepG, grnVal, i);
    bluVal = calculateVal(stepB, bluVal, i);

    analogWrite(redPin, redVal);   // Write current values to LED pins
    analogWrite(grnPin, grnVal);     
    analogWrite(bluPin, bluVal);

    if (++i > 1020)
      ramping = false ;
  }

With some setup code to trigger it:

void start_ramp ()
{
  i = 0 ;
  ramping = true ;
  last_ramp_time = millis () ;
}

Thanks for the fast reply Mark! I think I almost got it: I adjusted the code as you proposed, still I'm not sure why/how/where to trigger start_ramp

Sorry that I don't get it yet. This is how it looks now, I highlighted my changes:

#include <SoftwareSerial.h>
#include <TinyGPS.h>

long lat,lon;     // create variable for latitude and longitude object
long lat2,lon2;   // copy of lat lon

// Output RGB LED
int redPin = 9;   // Red LED,   connected to digital pin 9
int grnPin = 10;  // Green LED, connected to digital pin 10
int bluPin = 11;  // Blue LED,  connected to digital pin 11

// Color arrays
int black[3]  = { 0, 0, 0 };
int dimPurple[3] = { 20, 0, 30 };

// Set initial color
int redVal = black[0];
int grnVal = black[1]; 
int bluVal = black[2];

int ramping;                                        // CHANGED
unsigned long last_ramp_time;
int i=0;

int wait = 3;      // 10ms internal crossFade delay; increase for slower fades
int hold = 0;       // Optional hold when a color is complete, before the next crossFade
int repeat = 0;     // How many times should we loop before stopping? (0 for no stop)

// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;

SoftwareSerial gpsSerial(2,3); //create sensor connection
TinyGPS gps; // create GPS Object

void start_ramp ()                                       // CHANGED
{
  i = 0 ;
  ramping = true ;
  last_ramp_time = millis () ;
}

void setup() {
  
  pinMode(redPin, OUTPUT);   // sets the pins as output
  pinMode(grnPin, OUTPUT);   
  pinMode(bluPin, OUTPUT); 

  lat2=lat;                  // copy variables
  lon2=lon;

  Serial.begin(9600); // connect serial
  gpsSerial.begin(9600); // connect gps sensor
 
}

void loop() {
  while(gpsSerial.available()){     // check for gps data
    if(gps.encode(gpsSerial.read())){ // encode gps data
    gps.get_position(&lat,&lon);    // get latitude and longitude

    // serial display position
    Serial.println("Position: ");
    Serial.print("lat ");Serial.print(lat);Serial.print(" lon ");Serial.println(lon);
    }
  }
    if( lat <= 51440000 /*&& lat2 >= 51456000) && (lon <= 5468950 && lon2 >= 5468600)*/ ){
      start_ramp;                                       // CHANGED
      crossFade (black);
      crossFade (dimPurple);
  }
}





/* BELOW THIS LINE IS THE MATH -- YOU SHOULDN'T NEED TO CHANGE THIS FOR THE BASICS
* 
* The program works like this:
* Imagine a crossfade that moves the red LED from 0-10, 
*   the green from 0-5, and the blue from 10 to 7, in
*   ten steps.
*   We'd want to count the 10 steps and increase or 
*   decrease color values in evenly stepped increments.
*   Imagine a + indicates raising a value by 1, and a -
*   equals lowering it. Our 10 step fade would look like:
* 
*   1 2 3 4 5 6 7 8 9 10
* R + + + + + + + + + +
* G   +   +   +   +   +
* B     -     -     -
* 
* The red rises from 0 to 10 in ten steps, the green from 
* 0-5 in 5 steps, and the blue falls from 10 to 7 in three steps.
* 
* In the real program, the color percentages are converted to 
* 0-255 values, and there are 1020 steps (255*4).
* 
* To figure out how big a step there should be between one up- or
* down-tick of one of the LED values, we call calculateStep(), 
* which calculates the absolute gap between the start and end values, 
* and then divides that gap by 1020 to determine the size of the step  
* between adjustments in the value.
*/

int calculateStep(int prevValue, int endValue) {
  int step = endValue - prevValue; // What's the overall gap?
  if (step) {                      // If its non-zero, 
    step = 1020/step;              //   divide by 1020
  } 
  return step;
}

/* The next function is calculateVal. When the loop value, i,
*  reaches the step size appropriate for one of the
*  colors, it increases or decreases the value of that color by 1. 
*  (R, G, and B are each calculated separately.)
*/

int calculateVal(int step, int val, int i) {

  if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
    if (step > 0) {              //   increment the value if step is positive...
      val += 1;           
    } 
    else if (step < 0) {         //   ...or decrement it if step is negative
      val -= 1;
    } 
  }
  // Defensive driving: make sure val stays in the range 0-255
  if (val > 255) {
    val = 255;
  } 
  else if (val < 0) {
    val = 0;
  }
  return val;
}

/* crossFade() converts the percentage colors to a 
*  0-255 range, then loops 1020 times, checking to see if  
*  the value needs to be updated each time, then writing
*  the color values to the correct pins.
*/

void crossFade(int color[3]) {
  // Convert to 0-255
  int R = (color[0] * 255) / 100;
  int G = (color[1] * 255) / 100;
  int B = (color[2] * 255) / 100;

  int stepR = calculateStep(prevR, R);
  int stepG = calculateStep(prevG, G); 
  int stepB = calculateStep(prevB, B);

  if (ramping && millis()-last_ramp_time >= wait)                      // CHANGED
  {
    last_ramp_time += wait ;
    redVal = calculateVal(stepR, redVal, i);
    grnVal = calculateVal(stepG, grnVal, i);
    bluVal = calculateVal(stepB, bluVal, i);

    analogWrite(redPin, redVal);   // Write current values to LED pins
    analogWrite(grnPin, grnVal);     
    analogWrite(bluPin, bluVal);

    if (++i > 1020)
      ramping = false ;
  }
  
  // Update current values for next loop
  prevR = redVal; 
  prevG = grnVal; 
  prevB = bluVal;
  delay(hold);
}delay(hold);
}

Wrap your mind back to the second year of high school...
dV/dT is the basic function you're looking for...

Move the Value across the range / divided by the number of available Time steps.

Of course that's for a linear ramp - I'll let you figure out a correction map to compensate for the non-linear nature of LED lights.

Hi lastchancename, thanks for your reply.

I've got a non-linear ramp in the code already, it's just that it uses a delay at the end to control the speed of pulse which I'm trying to get rid of as it's blocking the gps data input.

I think Mark's answer is the key, yet I didn't get it working so far…

Maybe someone can explain me how to trigger the fade with Mark's solution?

I gave you a function specifically to trigger it - how is that hard to understand? You will have to figure out
the variable declarations - you have to do some of the work!

Yes of course, I'm on it.

I set up those global variables:

boolean ramping;
unsigned long last_ramp_time;
int i=0;

put this before the loop:

void start_ramp ()
{
  i = 0 ;
  ramping = true ;
  last_ramp_time = millis () ;
}

And this is how I tried to trigger it:

void loop()
{
  start_ramp;
  crossFade(black);
  crossFade(dimBlue);
  }
}

Why is it still doing nothing?

This is the whole code I'm using atm:

// Output
int redPin = 9;   // Red LED,   connected to digital pin 9
int grnPin = 10;  // Green LED, connected to digital pin 10
int bluPin = 11;  // Blue LED,  connected to digital pin 11

// Color arrays
int black[3]  = { 0, 0, 0 };
int dimBlue[3]  = { 40, 0, 30 };

boolean ramping = false;
unsigned long last_ramp_time;
int i=0;
int wait = 10;

// Set initial color
int redVal = black[0];
int grnVal = black[1]; 
int bluVal = black[2];

// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;

// Set up the LED outputs
void setup()
{
  pinMode(redPin, OUTPUT);   // sets the pins as output
  pinMode(grnPin, OUTPUT);   
  pinMode(bluPin, OUTPUT); 

  start_ramp;
}

int calculateStep(int prevValue, int endValue) {
  int step = endValue - prevValue; // What's the overall gap?
  if (step) {                      // If its non-zero, 
    step = 1020/step;              //   divide by 1020
  } 
  return step;
}

int calculateVal(int step, int val, int i) {

  if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
    if (step > 0) {              //   increment the value if step is positive...
      val += 1;           
    } 
    else if (step < 0) {         //   ...or decrement it if step is negative
      val -= 1;
    } 
  }
  // Defensive driving: make sure val stays in the range 0-255
  if (val > 255) {
    val = 255;
  } 
  else if (val < 0) {
    val = 0;
  }
  return val;
}

void crossFade(int color[3]) {
  // Convert to 0-255
  int R = (color[0] * 255) / 100;
  int G = (color[1] * 255) / 100;
  int B = (color[2] * 255) / 100;

  int stepR = calculateStep(prevR, R);
  int stepG = calculateStep(prevG, G); 
  int stepB = calculateStep(prevB, B);

  if (ramping && millis()-last_ramp_time >= wait)
  {
    last_ramp_time += wait ;
    redVal = calculateVal(stepR, redVal, i);
    grnVal = calculateVal(stepG, grnVal, i);
    bluVal = calculateVal(stepB, bluVal, i);

    analogWrite(redPin, redVal);   // Write current values to LED pins
    analogWrite(grnPin, grnVal);     
    analogWrite(bluPin, bluVal);

    if (++i > 1020)
      ramping = false ;
  
  }
  // Update current values for next loop
  prevR = redVal; 
  prevG = grnVal; 
  prevB = bluVal;
}


void start_ramp ()
{
  i = 0 ;
  ramping = true ;
  last_ramp_time = millis () ;
}


// Main program: list the order of crossfades
void loop()
{
  start_ramp;
  crossFade(black);
  crossFade(dimBlue);
}

Not sure if this is your problem but I think

void loop()
{
  start_ramp;
  crossFade(black);
  crossFade(dimBlue);
  }
}

should be

void loop()
{ 
  start_ramp();     
  crossFade(black);
  crossFade(dimBlue);
  }
}

You call a function with function_name() rather than just function_name

EDIT: after I posted this, I noticed you made the same easy-to-fix mistake in setup() too.

Of course! Thank you. The LED started blinking but merely uncontrollable. Only with a wait value around 3 there is some nervous blinking.

This is the code at the moment:

#include <SoftwareSerial.h>
#include <TinyGPS.h>

long lat,lon;     // create variable for latitude and longitude object
long lat2,lon2;   // copy of lat lon

// Output RGB LED
int redPin = 9;   // Red LED,   connected to digital pin 9
int grnPin = 10;  // Green LED, connected to digital pin 10
int bluPin = 11;  // Blue LED,  connected to digital pin 11

// Color arrays
int black[3]  = { 0, 0, 0 };
int dimPurple[3] = { 20, 0, 30 };

// Set initial color
int redVal = black[0];
int grnVal = black[1]; 
int bluVal = black[2];

boolean ramping;
unsigned long last_ramp_time;
int i=0;

int wait = 3;      // 10ms internal crossFade delay; increase for slower fades
int hold = 0;       // Optional hold when a color is complete, before the next crossFade
int repeat = 0;     // How many times should we loop before stopping? (0 for no stop)

// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;

SoftwareSerial gpsSerial(2,3); //create sensor connection
TinyGPS gps; // create GPS Object

void start_ramp ()                                       
{
  i = 0 ;
  ramping = true ;
  last_ramp_time = millis () ;
}

void setup() {
  
  pinMode(redPin, OUTPUT);   // sets the pins as output
  pinMode(grnPin, OUTPUT);   
  pinMode(bluPin, OUTPUT); 

  lat2=lat;                  // copy variables
  lon2=lon;

  Serial.begin(9600); // connect serial
  gpsSerial.begin(9600); // connect gps sensor
 
}

void loop() {
  while(gpsSerial.available()){     // check for gps data
    if(gps.encode(gpsSerial.read())){ // encode gps data
    gps.get_position(&lat,&lon);    // get latitude and longitude

    // serial display position
    Serial.println("Position: ");
    Serial.print("lat ");Serial.print(lat);Serial.print(" lon ");Serial.println(lon);
    }
  }
    if( lat <= 51440000 /*&& lat2 >= 51456000) && (lon <= 5468950 && lon2 >= 5468600)*/ ){
      start_ramp();
      crossFade (black);
      crossFade (dimPurple);
      crossFade (black);
  }
}





/* BELOW THIS LINE IS THE MATH -- YOU SHOULDN'T NEED TO CHANGE THIS FOR THE BASICS
* 
* The program works like this:
* Imagine a crossfade that moves the red LED from 0-10, 
*   the green from 0-5, and the blue from 10 to 7, in
*   ten steps.
*   We'd want to count the 10 steps and increase or 
*   decrease color values in evenly stepped increments.
*   Imagine a + indicates raising a value by 1, and a -
*   equals lowering it. Our 10 step fade would look like:
* 
*   1 2 3 4 5 6 7 8 9 10
* R + + + + + + + + + +
* G   +   +   +   +   +
* B     -     -     -
* 
* The red rises from 0 to 10 in ten steps, the green from 
* 0-5 in 5 steps, and the blue falls from 10 to 7 in three steps.
* 
* In the real program, the color percentages are converted to 
* 0-255 values, and there are 1020 steps (255*4).
* 
* To figure out how big a step there should be between one up- or
* down-tick of one of the LED values, we call calculateStep(), 
* which calculates the absolute gap between the start and end values, 
* and then divides that gap by 1020 to determine the size of the step  
* between adjustments in the value.
*/

int calculateStep(int prevValue, int endValue) {
  int step = endValue - prevValue; // What's the overall gap?
  if (step) {                      // If its non-zero, 
    step = 1020/step;              //   divide by 1020
  } 
  return step;
}

/* The next function is calculateVal. When the loop value, i,
*  reaches the step size appropriate for one of the
*  colors, it increases or decreases the value of that color by 1. 
*  (R, G, and B are each calculated separately.)
*/

int calculateVal(int step, int val, int i) {

  if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
    if (step > 0) {              //   increment the value if step is positive...
      val += 1;           
    } 
    else if (step < 0) {         //   ...or decrement it if step is negative
      val -= 1;
    } 
  }
  // Defensive driving: make sure val stays in the range 0-255
  if (val > 255) {
    val = 255;
  } 
  else if (val < 0) {
    val = 0;
  }
  return val;
}

/* crossFade() converts the percentage colors to a 
*  0-255 range, then loops 1020 times, checking to see if  
*  the value needs to be updated each time, then writing
*  the color values to the correct pins.
*/

void crossFade(int color[3]) {
  // Convert to 0-255
  int R = (color[0] * 255) / 100;
  int G = (color[1] * 255) / 100;
  int B = (color[2] * 255) / 100;

  int stepR = calculateStep(prevR, R);
  int stepG = calculateStep(prevG, G); 
  int stepB = calculateStep(prevB, B);

  if (ramping && millis()-last_ramp_time >= wait)                      // CHANGED
  {
    last_ramp_time += wait ;
    redVal = calculateVal(stepR, redVal, i);
    grnVal = calculateVal(stepG, grnVal, i);
    bluVal = calculateVal(stepB, bluVal, i);

    analogWrite(redPin, redVal);   // Write current values to LED pins
    analogWrite(grnPin, grnVal);     
    analogWrite(bluPin, bluVal);

    if (++i > 1020)
      ramping = false ;
  }
  
  // Update current values for next loop
  prevR = redVal; 
  prevG = grnVal; 
  prevB = bluVal;
  delay(hold);
}