#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// OLED display width and height, in pixels
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

// Declaration for SSD1306 display connected using I2C
#define OLED_RESET    -1  // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// Define joystick pin connections
#define JOYSTICK_X_PIN 34 // Pin ADC untuk sumbu X
#define JOYSTICK_Y_PIN 35 // Pin ADC untuk sumbu Y

void setup() {
  // Initialize serial for debugging
  Serial.begin(115200);
  
  // Initialize the OLED display
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  // Clear the buffer
  display.clearDisplay();
  
  // Display welcome message
  display.setTextSize(1);             // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE);        // Draw white text
  display.setCursor(0, 0);            // Start at top-left corner
  display.println(F("Joystick OLED"));
  display.display();  
  delay(1000);
}

void loop() {
  // Read the analog values from the joystick
  int xValue = analogRead(JOYSTICK_X_PIN);
  int yValue = analogRead(JOYSTICK_Y_PIN);

  // Display the joystick values on OLED
  display.clearDisplay(); // Clear previous contents
  
  // Print the values for X and Y
  display.setTextSize(2); // Larger font size
  display.setCursor(0, 0);
  display.print("X: ");
  display.println(xValue);
  
  display.setCursor(0, 30);
  display.print("Y: ");
  display.println(yValue);
  
  display.display(); // Update the display with new content
  
  // Print the values to serial monitor for debugging
  Serial.print("X: ");
  Serial.print(xValue);
  Serial.print(" | Y: ");
  Serial.println(yValue);
  
  delay(200); // Short delay for stability
}