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

// Pin definitions
const int firePin = 27;
const int dhtPin = 15;
const int relayPin = 14;

// Threshold values
const int fireThreshold = 80;
const int tempThreshold = 80;
const int humThreshold = 80;

// DHT setup
#define DHTTYPE DHT11
DHT dht(dhtPin, DHTTYPE);

// OLED setup
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

// Variables
float temperature = 0.0;
float humidity = 0.0;
int fireValue = 0;

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

  // Initialize OLED
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println("SSD1306 allocation failed");
    for (;;);
  }
  display.clearDisplay();
  display.display();

  // Initialize DHT sensor
  dht.begin();

  // Set relay pin as output
  pinMode(relayPin, OUTPUT);
}

void loop() {
  // Read temperature and humidity
  temperature = dht.readTemperature();
  humidity = dht.readHumidity();

  // Read fire sensor value from potentiometer and map to 0-100
  fireValue = map(analogRead(firePin), 0, 4095, 0, 100);

  // Control relay based on sensor values
  // Turn OFF the relay if any value exceeds the threshold
  if (temperature > tempThreshold || humidity > humThreshold || fireValue > fireThreshold) {
    digitalWrite(relayPin, LOW);  // Turn OFF relay
  } else {
    digitalWrite(relayPin, HIGH); // Turn ON relay
  }

  // Update OLED display
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);

  // Display system name
  display.setCursor(0, 0);
  display.println("BMS SYS");

  // Display relay status
  display.setCursor(0, 15);
  if (digitalRead(relayPin) == HIGH) {
    display.println("M *"); // Relay ON (active)
  } else {
    display.println("M -"); // Relay OFF (inactive)
  }

  // Display sensor values
  display.setCursor(0, 35);
  display.print("Temp: ");
  display.print(temperature);
  display.print("C");

  display.setCursor(0, 45);
  display.print("Hum: ");
  display.print(humidity);
  display.print("%");

  display.setCursor(0, 55);
  display.print("Fire: ");
  display.print(fireValue);

  // Display everything
  display.display();

  // Delay for stability
  delay(1000);
}
NOCOMNCVCCGNDINLED1PWRRelay Module