- 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.
Asked
Active
Viewed 110 times
1
Tokthebloke
- 11
- 2
1 Answers
2
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.
Majenko
- 105,851
- 5
- 82
- 139