0

I am trying to use a joystick for controlling something, but the only way I can control it is by having a direction to a corner instead of a side. For example, I would read up when the joystick points to the top left corner. I do that with an if x is greater than 500 (the midpoint) and if the y is greater than 500. Is there a way to make it read when it goes to a side instead of a corner?

if(analogRead(0) < 500 && analogRead(1) < 500){
    y--;
  } else if (analogRead(0) > 500 && analogRead(1) < 500){
    x++;
  } else if (analogRead(0) < 500 && analogRead(1) > 500){
    x--;
  } else if(analogRead(0)>500 && analogRead(1)>500){
    y++; 
  } 

I also do know that this is very badly written code, but this code is only for trying to read from a side rather than a corner.

potato
  • 21
  • 1
  • 5

1 Answers1

0

Transform your X and Y values into an angle and distance from the center, then compare against the angle.

Using this answer you can do the conversion:

const radianAngle = Math.atan2(y,x);

Then compare it agains the four quadrants:

0 <= angle < Pi/2 (quadrant A)
Pi/2 <= angle < Pi (quadrant B)
Pi <= angle < 3Pi/2 (Quadrant C)
3Pi/2 <= angle <= 2Pi (Quadrant D)

Than take a decision acording to each quadrant you are.

Edit: The original question doesn't say what language is used, so by the syntax I guesses (erroneously) that it was Javascript, but it's Java.

For Java the logic is the same, it also provides the atan2 function.

The implementation will be like:

double x = analogRead(0);
double y = analogRead(1);

double angle = Math.atan2(x, y);
int quadrant = (int) Math.max(1, Math.ceil(2 * angle / Math.PI));

The quadrant variable will be a quadrant from 1 to 4, you can use it value to take a decision.

Elias Soares
  • 9,884
  • 4
  • 29
  • 59