I am using the following code to determin where the thumb joystick is positioned:
const int Left = 1;
const int Right = 2;
const int Up = 3;
const int Down = 4;
const int Center = 0;
int lastButton = -1;
int xpin = 4;
int ypin = 5;
int xAxis;
int yAxis;
char* myStrings[]={"Left","Right","Up","Down"};
int button;
void setup() {
Serial.begin(9600);
}
void loop() {
xAxis=map(analogRead(xpin), 0, 1023, 0, 10);
yAxis=map(analogRead(ypin), 0, 1023, 0, 10);
if (button == lastButton) {
//Serial.println(0);
//button = 0;
delay(50);
} else {
if (xAxis < 4 ) {
button = Left;
}
else if (xAxis > 6 ) {
button = Right;
}
if (yAxis < 4 ) {
button = Down;
}
else if (yAxis > 6 ) {
button = Up;
}
Serial.println(myStrings[button-1]);
button = 0;
delay(50);
}
lastButton = button;
}
The code above works just fine on my arduino but i am looking to only get the postion ONCE and not every second while its held there.
How can i change the code to only take just one value until its centered (0) again?
Example:
If i move the joystick to the left it reads:
Left
Left
Left
Left
etc etc until i release it.
What i am looking to do is this:
Left
then it stops until i release it.
Any help would be great!
update
if (xAxis ==5 ) {
button = Center;
}
if (yAxis ==5 ) {
button = Center;
}
Seems to work well with Up and Down but not really for Left and Right. Sometimes it works, more often it doesn’t.
Remember where you were at the last iteration and compare to that to see if it has changed:
Complete cleaned up code: