Can I map a value up to a certain point, and from there it going down?

Hi everyone,

Is there a way to map a constant changing value (0-200) to be 0 at 0, and 255 when it reaches 100, and back down to 0 when it reaches 200? I can't figure out a way to code this. Would love to hear from you if you have any ideas how to fix this problem I have.

What I have now is: brightness map(val, 0, 100, 0, 255);

This works but only up to 100, when I exceed 100, it goes immediately down to 0 but has to be going back in reverse (255 to 0).

Using min should work:

value = map(min(val, 100), 0, 100, 0, 255);

Thanks, that works. But how do I make it go back down (from 255 to 0) when the val goes from 100 to 200?

If the input value is always in the range 0..200 then you could map that value to the range 0..510. After that you test if the value is above 255 and if so you do something like: value = 255 - (value - 255).

The MultiMap library may be of interest.

that's simply this what you want, right?



void setup() {
  Serial.begin(115200);

  for(int val=0; val<201; ++val){
    int value;
    if(val<101) value = map(val, 0, 100, 0, 255);
    else value = map(val, 100, 200, 255, 0);
    Serial.print(val);
    Serial.print(" -> ");
    Serial.println(value);
  }

}

void loop() {
  // put your main code here, to run repeatedly:

}

hope that helps...

1 Like

The general equation is y = 1-abs(x)

So

brightness = (100 - abs(input - 100) ) * 255 / 100;
or
brightness = map( (100 - abs(input - 100) ), 0, 100, 0, 255);

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.