#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// --- OLED Display Settings ---
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1 // -1 because it shares the ESP32 reset pin
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// --- Pin Definitions (Matching your JSON) ---
const int gasSensorPin = 34; // Gas Sensor AOUT
const int buzzerPin = 25; // Buzzer Signal
const int gasThreshold = 2000; // Trigger threshold (ESP32 ADC goes 0-4095)
void setup() {
// Start the serial monitor for debugging
Serial.begin(115200);
// Configure pin modes
pinMode(buzzerPin, OUTPUT);
pinMode(gasSensorPin, INPUT); // GPIO 34 is input-only, explicitly defining it
// Initialize the OLED display (I2C address 0x3C matches your JSON)
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed. Check wiring!"));
for(;;); // Halt the system if display fails
}
// Startup Screen
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 20);
display.println("Initializing...");
display.display();
delay(2000); // Give the sensor a brief moment to warm up
}
void loop() {
// 1. Read the analog data from the gas sensor
int gasValue = analogRead(gasSensorPin);
// Print to Serial Monitor for debugging
Serial.print("Current Gas Level: ");
Serial.println(gasValue);
// 2. Prepare the OLED Display
display.clearDisplay();
// Header Text
display.setCursor(0, 0);
display.setTextSize(1);
display.println("Gas Leak Detector");
display.drawLine(0, 10, 128, 10, WHITE); // Draw a separator line
// Display the current sensor value
display.setCursor(0, 20);
display.setTextSize(2);
display.print("Val: ");
display.print(gasValue);
// 3. Evaluate the Gas Level against the Threshold
display.setCursor(0, 45);
display.setTextSize(1);
if (gasValue > gasThreshold) {
digitalWrite(buzzerPin, HIGH); // Turn the buzzer ON
display.println("! DANGER: GAS !");
} else {
digitalWrite(buzzerPin, LOW); // Ensure the buzzer is OFF
display.println("Status: Normal");
}
// 4. Push the drawing to the screen
display.display();
// Wait half a second before taking the next reading
delay(500);
}