• I am trying to use the Arduino MAP function to allow me to PWM 4 LEDs between 0 and full brightness. I guess the tricky part is that the joystick neutral position is at the venter of the range of the potentiometers so the analog voltage to the inputs is at +2.5V when the joystick at neutral). Ideally I want to make a red LED that is associated with the Y axis to go from 0 to full as the joystick is pushed away. Similarly, I want a blue LED associated with the Y axis to go from 0 to Full on when the joystick is pulled toward me. I want to duplicate that action for the X axis with green and yellow LEDS but I can't seem to be able to figure out how to compensate for the 2.5V offset* I hoped I could just use mapping of the values.
  • 1
    Yes, just map 2.5-5 to 0-255 and analoWrite that value – Sim Son Nov 4 '20 at 6:25
  • int x=analogRead(A0);if (x >=512) red=(x-512)/2; etc. – DataFiddler Nov 4 '20 at 11:22
  • Thanks to all who have responded. I have tried Sim Son's approach and as unsuccessful. I will have to test the other techniques.I'll report back on progress. – Tokthebloke Nov 4 '20 at 22:06

There's a number of steps you need to go through:

  1. Read the ADC to get the joystick position
  2. Subtract 50% of the full range (512) to get a ±512 value
  3. Note the sign to get the direction
  4. Take the absolute value to get the distance
  5. Subtract a small amount to create a "dead zone" in the centre of the joystick
  6. Map the result to 0-255 for the PWM.

The code might look like (note: untested):

int y = analogRead(0);    // Get the current value
y -= 512;                 // Subtract 512

int pin = 2;              // Unless otherwise told, use pin 2
if (y < 0) {              // If it's negative...
    pin = 3;              //    then we'll use pin 3 instead

y = abs(y);               // Take the absolute value (discard the sign)
y -= 20;                  // subtract 20 for a dead zone
If (y < 0) y = 0;         // zero any negative
y = map(0, 492, 0, 255);  // map the new full range of 0-492 to 0-255
analogWrite(pin, y);      // light the LED on the pin we chose above.

And do the exact same thing for X with different pins.

  • If you subtract 20 from y before mapping, won't that cause some negative values of y? (The range would be -20 to 492 instead of 0-512.) What does map do with out-of-range values? – Duncan C Nov 4 '20 at 18:06
  • I'd suggest changing y -= 20; to if y <= 20 y = 0; instead. – Duncan C Nov 4 '20 at 18:07
  • Good question. You should do it at 0. – Majenko Nov 4 '20 at 18:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.