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

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

#define OLED_RESET    -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

QRCode qrcode;
uint8_t qrcodeData[qrcode_getBufferSize(3)]; // Buffer for a version 3 QR code

void setup() {
  // Initialize Serial
  Serial.begin(115200);
  
  // Initialize the OLED display
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);

  // Generate a QR code
  const char *text = "https://www.example.com";
  qrcode_initText(&qrcode, qrcodeData, 3, 0, text);

  // Display the QR code on the OLED
  displayQRCode(&qrcode);
}

void loop() {
  // You can update the QR code here if needed
}

void displayQRCode(QRCode *qrcode) {
  int offsetX = (SCREEN_WIDTH - qrcode->size * 2) / 2;
  int offsetY = (SCREEN_HEIGHT - qrcode->size * 2) / 2;
  
  for (uint8_t y = 0; y < qrcode->size; y++) {
    for (uint8_t x = 0; x < qrcode->size; x++) {
      if (qrcode_getModule(qrcode, x, y)) {
        display.fillRect(offsetX + x * 2, offsetY + y * 2, 2, 2, SSD1306_WHITE);
      } else {
        display.fillRect(offsetX + x * 2, offsetY + y * 2, 2, 2, SSD1306_BLACK);
      }
    }
  }
  
  display.display();
}