Search code examples
arduinofloating-pointfilesize

How to remove floats or reduce actual file size of code function? (Arduino)


I am trying to get my arduino code for gemma, with neopixels, which has 5310 bytes of memory smaller so I can get more things into the program.
Currently I am trying to remove floats / reduce the size of the code snippet below:

void gradient(Color c1, Color c2, float time) {
  for (float i = 0; i < time; i += 0.001) {
    Color result(0, 0, 0);
    result.Red = c1.Red * (1 - (i / time)) + c2.Red * (i / time);
    result.Green = c1.Green * (1 - (i / time)) + c2.Green * (i / time);
    result.Blue = c1.Blue * (1 - (i / time)) + c2.Blue * (i / time);
    for (uint8_t x = 0; x < 20; x++)pixels.setPixelColor(x, result.Red, result.Green, result.Blue);
    pixels.show();
    delay(1);
  }
}

I managed to reduce it by 30 bytes to:

void gradient(Color c1, Color c2, float time) {
  float stepsize = 0.01;    // Stepsize in seconds
  float lambda;
  int maxiter = (int) (time/ stepsize);
  Color result(0, 0, 0);
  for (int i = 0; i <= maxiter; i++) {
    lambda = (float) i / maxiter;
    result.Red = c1.Red * (1 - lambda) + c2.Red * (lambda);
    result.Green = c1.Green * (1 - lambda) + c2.Green * (lambda);
    result.Blue = c1.Blue * (1 - lambda) + c2.Blue * (lambda);
    for (uint8_t x = 0; x < 20; x++)pixels.setPixelColor(x, result.Red, result.Green, result.Blue);
    pixels.show();
    delay(stepsize * 1000);  // delay in milliseconds
  }
}

But am trying still to make it smaller.
For those wondering the Color object is just an object with 3 ints called Red, Green and Blue. An example usage of this code would be:

gradient(Color(255, 0, 0), Color(0, 255, 0), 2);

Which would be a gradient from Red to Green over 2 seconds.
Thanks in advance!


Solution

  • If you can pull "delay()" out of all your code, it seems to avoid including a 100 byte size library? idk tbh, but here is my suggested modification, which in my testing saves 100 bytes of memory:

        void gradient(Color c1, Color c2, float time) {
      float stepsize = 0.01;    // Stepsize in seconds
      float lambda;
      int maxiter = (int) (time/ stepsize);
      Color result(0, 0, 0);
      for (int i = 0; i <= maxiter; i++) {
        lambda = (float) i / maxiter;
        result.Red = c1.Red * (1 - lambda) + c2.Red * (lambda);
        result.Green = c1.Green * (1 - lambda) + c2.Green * (lambda);
        result.Blue = c1.Blue * (1 - lambda) + c2.Blue * (lambda);
        for (uint8_t x = 0; x < 20; x++)pixels.setPixelColor(x, result.Red, result.Green, result.Blue);
        pixels.show();
        //delay(stepsize * 1000);  // delay in milliseconds
    
        long lastTime=millis();
        long delayTime = stepsize * 1000;
        while(millis()-lastTime<delayTime){}
      }
    }