#include <ezButton.h>
#define X_PIN A0 // Arduino pin connected to VRX pin
#define Y_PIN A1 // Arduino pin connected to VRY pin
#define SW_PIN 0 // Arduino pin connected to SW pin
#define LEFT_THRESHOLD 400
#define RIGHT_THRESHOLD 800
#define UP_THRESHOLD 400
#define DOWN_THRESHOLD 800
#define COMMAND_NO 0x00
#define COMMAND_LEFT 0x01
#define COMMAND_RIGHT 0x02
#define COMMAND_UP 0x04
#define COMMAND_DOWN 0x08
ezButton button(SW_PIN);
int xValue = 0; // To store value of the X axis
int yValue = 0; // To store value of the Y axis
int bValue = 0; // To store value of the button
int command = COMMAND_NO;
int led_sel = 2;
int led_up = 3;
int led_r = 5;
int led_down = 7;
int led_l = 9;
void setup() {
pinMode(led_sel, OUTPUT);
pinMode(led_up, OUTPUT);
pinMode(led_r, OUTPUT);
pinMode(led_down, OUTPUT);
pinMode(led_l, OUTPUT);
Serial.begin(9600) ;
button.setDebounceTime(10); // set debounce time to 50 milliseconds
}
void loop() {
button.loop(); // MUST call the loop() function first
// read analog X and Y analog values
xValue = analogRead(X_PIN);
yValue = analogRead(Y_PIN);
// Read the button value
bValue = button.getState();
if (button.isPressed()) {
Serial.println("The button is pressed");
// TODO do something here
digitalWrite(led_sel,HIGH);
}
if (button.isReleased()) {
Serial.println("The button is released");
// TODO do something here
digitalWrite(led_sel,LOW);
}
// converts the analog value to commands
// reset commands
command = COMMAND_NO;
// check left/right commands
if (xValue < LEFT_THRESHOLD)
command = command | COMMAND_LEFT;
else if (xValue > RIGHT_THRESHOLD)
command = command | COMMAND_RIGHT;
// check up/down commands
if (yValue < UP_THRESHOLD)
command = command | COMMAND_UP;
else if (yValue > DOWN_THRESHOLD)
command = command | COMMAND_DOWN;
// NOTE: AT A TIME, THERE MAY BE NO COMMAND, ONE COMMAND OR TWO COMMANDS
// print command to serial and process command
if (command & COMMAND_LEFT) {
Serial.println("COMMAND LEFT");
// TODO: add your task here
digitalWrite(led_l,HIGH);
}
if (command & COMMAND_RIGHT) {
Serial.println("COMMAND RIGHT");
// TODO: add your task here
digitalWrite(led_r,HIGH);
}
if (command & COMMAND_UP) {
Serial.println("COMMAND DOWN");
// TODO: add your task here
digitalWrite(led_down,HIGH);
}
if (command & COMMAND_DOWN) {
Serial.println("COMMAND UP");
// TODO: add your task here
digitalWrite(led_up,HIGH);
}
else {
digitalWrite(led_l,LOW);
digitalWrite(led_r,LOW);
digitalWrite(led_up,LOW);
digitalWrite(led_down,LOW);
}
// print data to Serial Monitor on Arduino IDE
Serial.print("x = ");
Serial.print(xValue);
Serial.print(", y = ");
Serial.print(yValue);
Serial.print(" : button = ");
Serial.println(bValue);
delay(1);
}