Increment and decrement problem with a joystick

Hello, my name is José and I´m fascinated with arduino.

I´m doing a little project with a joystick, I´m triying to increment and decrement a variable till it goes to a limit (I choose the limit obviusly :D) but I´ve tried several times with differents codes but still I don´t get the answer could you help me please.

That is the code i´m using right now:

byte yPin = A1; //VRY

int minima=400;
int maxima=1800;

int velocidad=minima;

void setup() {
 
pinMode(yPin, INPUT);
Serial.begin(9600);

}

void loop() {

velocidad=calcular_velocidad();
Serial.println(velocidad);
delay(200);
}

int calcular_velocidad(){

do{
if(analogRead(yPin)>=1022){
    velocidad=velocidad+100;
       return(velocidad);
    }
    
if (analogRead(yPin)<=2){
    velocidad=velocidad-100;
    return (velocidad);
    }
}while ((velocidad>minima)and(velocidad<maxima));

if(velocidad==minima){
return (minima);
  }
  
if(velocidad==maxima){
return (maxima);
  }

}

The problem is that variable "velocidad" always exceeds the limits, please if somebody can help I´ll appreciate a lot.

That is kind of pretzel logic... can you explain in simple terms what actions it is supposed to perform?

I think you need to reorganize your calcular_velocidad() function so that it only has one return. The way you have it the first return means that none of the rest of the function is used

And I agree with @aarg

...R

Hi guys thanks for the quick answer, the action to do with the joystick is when I press the joystick up it would have to increase of 100 numbers until I reach the limit or release the it... the opposite when I press down.

How do you define "press up" and "press down"?

press up when the lever go forward and press down when the lever go backward.

jotaPedro:
press up when the lever go forward and press down when the lever go backward.

Define "forward" and "backward". Is it a digital or analog stick? Do you want it to increase 100 only once for each "forward/backward" or increase continuously at some fixed rate?

I´m using the joystick that you can see in the picture attached, it´s an analog joystick.

arduino-joystick-.jpg

jotaPedro:
Hi guys thanks for the quick answer,

So, have you tried modifying your program like I suggested. If so, and if it still does not work, post the latest version.

...R

I´m still at work, as soon I get home I´ll try to make some changes to code...