#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

const int mq3SensorPin = A0; // MQ-3 sensor connected to A0
const int warmupTime = 60;   // Warm-up time in seconds (1 minute)

void setup() {
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Initialize OLED with I2C address 0x3C
  display.clearDisplay();
  display.setTextColor(WHITE);

  // Display title and warming up
  displayTitle("Breath Analyzer");
  delay(2000); // Display title for 2 seconds
  displayWarmup();
}

void loop() {
  // Read sensor value
  int sensorValue = analogRead(mq3SensorPin);

  // Display alcohol detection
  displayAlcoholLevel(sensorValue);
  delay(500); // Refresh every 500ms
}

// Function to display title
void displayTitle(const char* title) {
  display.clearDisplay();
  display.setTextSize(1);

  // Title on top center
  int16_t x1, y1;
  uint16_t w, h;
  display.getTextBounds(title, 0, 0, &x1, &y1, &w, &h);
  display.setCursor((128 - w) / 2, 0); // Top center
  display.println(title);

  display.display();
}

// Function to display warming-up progress
void displayWarmup() {
  for (int i = 0; i <= 100; i++) {
    display.clearDisplay();

    // Display title
    display.setTextSize(1);
    display.setCursor(0, 0);
    display.println("Breath Analyzer");

    // Display "Warming up"
    display.setTextSize(1);
    display.setCursor(10, 20); // Slightly below the title
    display.println("Warming up...");

    // Display progress percentage
    char progress[10];
    sprintf(progress, "%d%%", i);
    display.setCursor(50, 40); // Centered in the lower half
    display.println(progress);

    display.display();
    delay(warmupTime * 10); // Convert 60 seconds to 100 steps
  }
}

// Function to display alcohol detection level
void displayAlcoholLevel(int value) {
  display.clearDisplay();

  // Display title
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.println("Breath Analyzer");

  // Display alcohol level
  display.setTextSize(1);
  display.setCursor(20, 20); // Centered in the display
  if (value < 700) {
    display.println("Low Levels");
  } else {
    display.println("High Levels");
  }

  display.display();
}
