Using Map() multiple times on same input/output

Hello there, first post so hoping this is the correct place!

I am trying to make a RGB LED light up and down with a potentiometer. What I want is to use the map function (or any other way to make it happen), to make it light up from 0-512, then dim it down between 513-1023.

So far, this is the relevant part of my code:

 int potPositionR1;

void loop()  {
  int potPositionR1 = analogRead(A0);

  
  potPositionR1 = map(potPositionR1, 0, 512, 0, 255);
  potPositionR1 = map(potPositionR1, 513, 1023, 255, 0);

  analogWrite(9, potPositionR1);

delay(50);

}

Interestingly enough, this code makes it dim down as if I had it mapped (0, 1023, 255, 0)...

Is there any way for me to make it work so that I can map the same output and input to different things at different values from the potentiometer?

How about…

if (potPositionR1 <= 512) {
  ...
} else {
  ...
}

quarrry:
Hello there, first post so hoping this is the correct place!

I am trying to make a RGB LED light up and down with a potentiometer. What I want is to use the map function (or any other way to make it happen), to make it light up from 0-512, then dim it down between 513-1023.

something like this maybe…

(compiles, NOT tested):

int potPositionR1;

void setup() {
  //nothing here for now...
}

void loop()  {
  int potPositionR1 = analogRead(A0);


  if (potPositionR1 < 513) {
    //light up
    potPositionR1 = map(potPositionR1, 0, 512, 0, 255);
  }
  else {
    //dim
    potPositionR1 = map(potPositionR1, 513, 1023, 255, 0);
  }

  analogWrite(9, potPositionR1);

  delay(50);

}

hope that helps…

PS: @pcbbc beat me to it! :stuck_out_tongue:

Thank you both, pcbbc and sherzaad! It worked just how I wanted it to!
I had messed around with if else statements earlier today but this is my first week of arduino and I couldn't make it work (also no help googling like a madman). Had not thought about putting the mapping into the if else statements themselves :slight_smile:

Mapping between two ranges where both start or end at 0 can be done with a simple multiply or divide.

For example, 0…1023 → 0…255 is equivalent to dividing by 4.

  if (potPositionR1 < 512)
    potPositionR1 /= 2;  // 0..511 -> 0..255
  else
    potPositionR1 = (1023 - potPositionR1) / 2;  // 512..1023 -> 511..0 -> 255..0

What colors do you want the different position of the pot to map to?

-jim lee