Arduino: Record value of the encoder only once at the instant the PS2 joystick reads 128 (when at rest)
If you only want to catch this event once - when it first hits 128, you just need a global variable to flag when you've seen it:

boolean g_bSeen128 = false;

void setup()
{
    // ... whatever
}

void loop()
{
    // ... your existing code

    // catch first time we see 128
    if (!g_bSeen128 &amp;&amp; Y_axis == 128)
    {
        // ... do whatever you need here. e.g.
        Setpoint = encoder0Pos;
        myPID.Compute();
        analogWrite(pwm, Output);

        // stop the event being caught next time
        g_bSeen128 = true;
    }

    // from comments below - to just ignore consecutive 128's, add this:
    if (Y_axis != 128) g_bSeen128 = false;

    // ... your existing code

}


If you only want to do something if the input changes, no matter what it is, you can keep track of the last input:

int g_nLastInput = -1;

void setup()
{
    // ... whatever
}

void loop()
{
    // get input
    int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

    // if input has changed ...
    if (Y_axis != g_nLastInput)
    {
        // ... save latest input
        g_nLastInput = Y_axis;

        // now process the change, e.g.
        if (Y_axis == 128)
        {
            // ... do something special for 128
        }
        else
        {
            // ... do something else for other inputs
        }
    }
}


I'm not sure what you're trying to do with the PWM when you get inputs either side of 128, it seems to me that you might want to go in one direction if the input is less than 128 and go in the other direction if it's greater than 128. In either case, the magnitude of your PWM speed should just reflect how far you are from 128 in either direction. So subtracting 128 from your input will give a delta that is +/- 128 and we can scale its absolute value to 0..255 for the PWM setting.

If that's correct, an alternative way of coding your original logic might be like this:

void loop()
{
    // get input
    int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

    Input = encoder0Pos;

    // if input has changed ...
    if (Y_axis != g_nLastInput)
    {
        // ... save latest input
        g_nLastInput = Y_axis;

        // now process the change
        int nDelta = Y_axis - 128;

        if (nDelta == 0)
        {
            // i.e. Y_axis is 128
            Setpoint = encoder0Pos;
            myPID.Compute();
            analogWrite(pwm, Output);
        }
        else
        {
            // choose direction
            digitalWrite(dir, (nDelta &gt; 0) ? HIGH : LOW);

            // set PWM speed scaled to 0..255
            analogWrite(pwm, abs(nDelta) * 2);
        }
    }
}