- 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 Answer
There's a number of steps you need to go through:
- Read the ADC to get the joystick position
- Subtract 50% of the full range (512) to get a ±512 value
- Note the sign to get the direction
- Take the absolute value to get the distance
- Subtract a small amount to create a "dead zone" in the centre of the joystick
- 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 CCommented Nov 4, 2020 at 18:06
-
I'd suggest changing
y -= 20;
toif y <= 20 y = 0;
instead.– Duncan CCommented Nov 4, 2020 at 18:07 -
int x=analogRead(A0);if (x >=512) red=(x-512)/2;
etc.