//DISPLAY WITH JOYSTICK
//Libraries
#include <Wire.h>
#include <U8g2lib.h>
//Select the option that matches the dimensions of the OLED
U8G2_SSD1306_128X64_NONAME_F_HW_I2C DISPA(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
//Pins for SDA and SCL
#define SDA 4
#define SCL 5
//Pin numbers
int LED = D9;
int JoyX = A2;
int JoyY = A1;
//Create string variable to show direction message in display
String Direction = "Hello";
//---------------------------------------------------------------------------------
void setup() {
//Turn on serial monitor
Serial.begin(9600);
//LED
pinMode(LED, OUTPUT);
//Joystick pinout
pinMode(JoyX, INPUT);
pinMode(JoyY, INPUT);
//SDA and SCL pinout
pinMode(SDA, OUTPUT);
pinMode(SCL, OUTPUT);
// Set I2C bus speed on board and both displays
Wire.setClock(100000);
DISPA.setBusClock(100000);
//Set I2C Adress (0x78/0x7A, or 0x3C/0x3D)
DISPA.setI2CAddress(0x78);
//Turn on OLED and get it ready to accept data
DISPA.begin();
//Select a font
DISPA.setFont(u8g2_font_logisoso16_tf );
//Make sure the display buffer is clear
DISPA.clearBuffer();
}
//---------------------------------------------------------------------------------
//Function to enter joystick values and know the direction
int signal(int a, int b) { //(X,Y)
if((a>=490 && a<=494)&&(b>=468 && b<=474)){ //STOP
return 0; //#s for each direction, bc Arduino IDE's functions don't return strings
}
else if (a==511){ //UP
return 1;
}
else if(a==0){ //DONW
return 2;
}
else if(b==0){ //LEFT
return 3;
}
else if(b==511){ //RIGHT
return 4;
}
}
//---------------------------------------------------------------------------------
void loop() {
//Clear display
DISPA.clearBuffer();
//LED and read analog values from joystick
digitalWrite(LED, HIGH);
int ValorX = analogRead(JoyX)/8;
int ValorY = analogRead(JoyY)/8;
//Show things in display
DISPA.setCursor(25, 20); //(X,Y)
DISPA.print("Joystick");
DISPA.setCursor(5, 40); //(X,Y)
DISPA.print("X: ");
DISPA.setCursor(25, 40); //(X,Y)
DISPA.print(ValorX);
DISPA.setCursor(75, 40); //(X,Y)
DISPA.print("Y: ");
DISPA.setCursor(95, 40); //(X,Y)
DISPA.print(ValorY);
//Enter analog values into the function to know direction
int DirNumb = signal(ValorX, ValorY);
//Assign string values to each value from the function
if(DirNumb == 0){
Direction = "STOP";
}
else if(DirNumb == 1){
Direction = "UP";
}
else if(DirNumb == 2){
Direction = "DOWN";
}
else if(DirNumb == 3){
Direction = "LEFT";
}
else if(DirNumb == 4){
Direction = "RIGHT";
}
DISPA.setCursor(50, 60); //(X,Y)
DISPA.print(Direction); //Print the direction in OLED
DISPA.sendBuffer(); //Command to show things on display
}