Search code examples
c++arduinosmoothing

Smooth an always updaing value?


How would you go about smoothing an always updating value, The code:

int nLEDs = 25; // Number of LED's 
int sensitivity = 1;

int incomingByte = 0; 
int r = 0;
int g = 0;
int b = 0;
int a = 0;

void loop() {

        if (Serial.available() > 0) {
          incomingByte = Serial.parseInt();
          a = (255 / 100) * (incomingByte * sensitivity);
        }

       // some code 
}

void fade(){
  for(int i=0;i<nLEDs;i++){
   r = a;
   g = 0;
   b = 0;

   FTLEDColour col = { r , g , b };
 }
}

void ColourFade(){
  for(int i=0;i<nLEDs;i++){
   r = a;
   g = 255 - a;
   b = 0;

   FTLEDColour col = { r , g , b };
  }
}

On the fade methods, How would you go about smoothing the changes in the values instead of just jumping? If this is possible.


Solution

  • Instead of this:

    value = NewValue
    

    Do something like this:

    value = (Value * 7 + NewValue + 7) / 8
    

    This will cause value to be 7/8 the old value and 1/8 the new value, causing it to gradually "drift" to the new value, rather than jumping there all at once.