// include the library code:
// #include <LiquidCrystal.h>
// // initialize the library with the numbers of the interface pins
// LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_LINES 2
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
// declare pins for the Joystick module
int posX = A0;
int posY = A1;
// create holders for the LCD position
int cursorCol = 0;
char values[] = {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'};
void setup() {
Serial.begin(9600);
// set up the LCD's number of columns and rows:
// lcd.begin(16, 2);
// // enable the LCD cursor so that it shows the current index
lcd.init();
lcd.backlight();
lcd.cursor();
}
void loop() {
char dirToMove = getDirection();
Serial.print(dirToMove);
Serial.print(", ");
moveCursor(dirToMove);
// Move the cursor back to the origin to update the display
lcd.setCursor(0, 0);
lcd.print((String)values);
// now move the cursor back to the current user-selected location
lcd.setCursor(cursorCol, 0);
// add a slight delay to keep from moving too fast! :)
delay(200);
}
// Moves the cursor in the specified direction
void moveCursor(char dirToMove) {
switch (getDirection()) {
case 'R': cursorCol += 1;
break;
case 'L': cursorCol -= 1;
break;
case 'U': values[cursorCol] += 1;
break;
case 'D': values[cursorCol] -= 1;
break;
default: break;
}
// some error handling
if (cursorCol >= 16) {
cursorCol = 0;
} if (cursorCol < 0) {
cursorCol = 15;
}
}
// Return the direction the joystick is being held
// L|R will take precedence over U|D
char getDirection() {
int X = analogRead(posX); int Y = analogRead(posY);
Serial.print("X:");
Serial.print(X);
Serial.print(", Y:");
Serial.println(Y);
// We care about x first, then y
// The range of both X/Y is [0, 1023]
if (X > 923)
{ return 'R';
//We are holding the joystick RIGHT
} else if (X < 100) {
return 'L';
//We are holding the joystick LEFT
} else if (Y > 923) {
return 'U';
//We are holding the joystick UP
} else if (Y < 100) {
return 'D';
//We are holding the joystick DOWN
} else {
return 'C';
//We are not holding the joystick in any specific direction
}
}