I am having some problems understanding why this code isn't working all the time. The code is supposed to read "x/y value obtained" if the joystick is in the center position, but if I move the joystick to the left / left up / left down the code prints "x value not obtained" even after the joystick is released. After I touch the joystick back to the right it starts work properly again.
// Freetronics 0LED joystick shield
int sensorValueY = analogRead(A2); //
int sensorValueX = analogRead(A3); //
if (sensorValueX == 507) {
Serial.println("X Value Obtained:");
}
else {
Serial.println("X Value Not Obtained:");
}
if (sensorValueY == 499) {
Serial.println("Y Value Obtained:");
}
else {
Serial.println("Y Value Not Obtained:");
}
}
if (sensorValueX == 507) {
Serial.println("X Value Obtained:");
}
else {
Serial.println("X Value Not Obtained:");
}
This section of code is looking for a very specific value and any other value will result in the "X Value Not Obtained:" message being printed. If the joystick does not return to exactly the position that gives a value of 507 you will get the outcome that you describe.
Try printing the value of sensorValueX and you will see what is going on.
Hi,
As UK has said, you will not get the same value each time the joystick returns to its resting position.
You need to add some hysteresis, as in look for values 502 to 512 to declare that yiu have centre position.
Do not rely on the centre values ever being exactly the same twice. Add some hysteresis based on reading the values and outputting them so that you see how much variation to allow for.
You should be able to just use values less than and greater than the centre range rather than a range for up/down etc. It will make the program marginally easier to write. If you make the centre range wider then, depending on what you want to do, you can ensure that the joystick is moved quite a bit before deciding that it is up, down etc, thus reducing the sensitivity if that suits your application.
Gates:
I am having some problems understanding why this code isn't working all the time. The code is supposed to read "x/y value obtained" if the joystick is in the center position, but if I move the joystick to the left / left up / left down the code prints "x value not obtained" even after the joystick is released. After I touch the joystick back to the right it starts work properly again.
because your joystick - mechanically - is not centering exactly after you release it. It's hardware, not an ideal logical object. You have to cope with what it actually does, not code to what it should in theory do.
In theory, there's no difference between theory and practise. But in practise, there usually is.