Simple calculation problem

Hi all!

I’m trying to build a simple LED fade function, and I’ve got it working just how I want it to, but I’ve fallen at the last hurdle… I have the following code that generates a number from 0-255 which is the “master brightness”

void RampUp() {
  if (alreadyon == 0) {
    for (int i = 270; i < 450; i++) {                             // 360 degrees of an imaginary circle.

      float angle = radians(i);                                       // Converts degrees to radians.
      brightness = (255 / 2) + (255 / 2) * sin(angle);    // Generates points on a sign wave.
      delay(5);                                                            // Delay between each point of sine wave.
    }
  }
}

I have 3 sets of LEDs I’m controlling, and I would like them to end up at different maximum brightnesses as such:

int PointerBrightness = 25;
int FrontBrightness = 20;
int RearBrightness = 50;

So I want to make some code like this:

void RampUp() {
  if (alreadyon == 0) {
    for (int i = 270; i < 450; i++) {                              // 360 degrees of an imaginary circle.

      float angle = radians(i);                                       // Converts degrees to radians.
      brightness = (255 / 2) + (255 / 2) * sin(angle);    // Generates points on a sign wave.
      analogWrite(PointerLEDPin, (PointerBrightness/255)*brightness); 
      analogWrite(FrontLEDPin, (FrontBrightness/255)*brightness);
      analogWrite(RearLEDPin, (RearBrightness/255)*brightness);
      valuet = (PointerBrightness/255)*brightness;
      delay(5);                                                       // Delay between each point of sine wave.
    }
  }
}

However, when I add the “(PointerBrightness/255)*brightness” I get nothing from the LED. using the serial monitor I see that the result of the calculation is 0. What am I doing wrong here…??

What is the result of 25/255 when both are integers ?

So do I need to set everything to float? Or better to multiply up to work in integers, then divide and round the result?

450nick: So do I need to set everything to float? Or better to multiply up to work in integers, then divide and round the result?

Yes, you can use scaled integer calculations to multiply by a fraction. Integer division truncates the result by default.

nice! Thanks chaps got it

450nick: However, when I add the "(PointerBrightness/255)*brightness" I get nothing from the LED. using the serial monitor I see that the result of the calculation is 0. What am I doing wrong here..??

One good way to avoid floats is to do the multiply before the divide: "brightness = (PointerBrightness*brightness)/255".

Be warned that since 'PointerBrightness' is an 'int', if 'brightness' is also an 'int' and the result of the multiplication is greater than 32767 you will get an integer overflow and the wrong answer.

When you do scaling you do it by powers of 2, like 256. Not powers of two minus one.