// hello.RP2040-XIAO.oled-echo.ino
//
// Seeed XIAO RP2040 OLED echo hello-world
// Adapted for a 0.96" SSD1306 I2C OLED display
// Generated inside Parley with model Gemini
// 3.1 Pro on September 24, 2026

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

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

// Initialize the display using the standard Wire (I2C) interface.
// On the XIAO RP2040, Wire defaults to SDA = GPIO 6, SCL = GPIO 7.
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

// Optional: if your J4 connector literally uses Pin 7 to supply 3.3V power:
// #define oledpower 7 

#define bufsize 25
char buf[bufsize];
int count = 0;

// setup
void setup() {
  Serial.begin(115200);

  // IF pin 7 is acting as a physical VCC power supply for the OLED, uncomment below:
  // pinMode(oledpower, OUTPUT);
  // digitalWrite(oledpower, HIGH);
  // delay(50); // wait briefly for the screen to power on

  // Initialize the OLED display at I2C address 0x3C
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println("OLED allocation failed");
    for(;;); // Loop forever if OLED is not found
  }
  
  // Clear the buffer and print a startup message
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println("Waiting for serial...");
  display.display();
}

// main loop
void loop() {
  char chr;
  
  // check for a char
  if (Serial.available()) {
    
    // read, save, and send char
    chr = Serial.read();
    buf[count] = chr;
    count += 1;
    buf[count] = 0;
    
    // reset buffer if it gets full
    if (count == (bufsize - 1)) {
      count = 0;
    }
    
    // Print to the computer's Serial Monitor
    Serial.print("hello.RP2040-XIAO.oled-echo.ino: you typed ");
    Serial.println(buf);
    
    // Update the OLED Screen
    display.clearDisplay();        // Erase previous text
    display.setCursor(0, 0);       // Start at top-left
    display.setTextSize(1);        // Normal text size
    display.println("You typed:");
    
    display.setCursor(0, 20);      // Move cursor down a bit
    display.setTextSize(2);        // Double text size for the typed letters
    display.println(buf);          // Print the character buffer
    
    display.display();             // Push changes to the screen
  }
}