#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#include <Stepper.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
#define LDR_PIN 34
#define MQ2_PIN 35
#define PIR_PIN 5
#define STEPPER_STEPS 2048
Stepper stepper(STEPPER_STEPS, 12, 14, 13, 15);
float oxygenThreshold = 70.0;
// Array for pulse graph (stores previous values for scrolling effect)
int pulseData[SCREEN_WIDTH] = {0};
void setup() {
Serial.begin(115200);
dht.begin();
pinMode(LDR_PIN, INPUT);
pinMode(MQ2_PIN, INPUT);
pinMode(PIR_PIN, INPUT);
stepper.setSpeed(10);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.clearDisplay();
display.display();
}
void loop() {
// Read sensors
int ldrValue = analogRead(LDR_PIN);
int mq2Value = analogRead(MQ2_PIN);
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
int motionDetected = digitalRead(PIR_PIN);
// Convert MQ2 reading to oxygen % (simple scaling)
float oxygenLevel = map(mq2Value, 0, 4095, 0, 100);
// ----- Serial Monitor Output -----
Serial.println("=== Sensor Readings ===");
Serial.print("Temperature (C): "); Serial.println(temperature);
Serial.print("Humidity (%): "); Serial.println(humidity);
Serial.print("Oxygen Level (%): "); Serial.println(oxygenLevel);
Serial.print("LDR Value: "); Serial.println(ldrValue);
Serial.print("Motion Detected: "); Serial.println(motionDetected ? "Yes" : "No");
Serial.println("========================\n");
// Shift pulse data to left
for (int i = 0; i < SCREEN_WIDTH - 1; i++) {
pulseData[i] = pulseData[i + 1];
}
// Map new LDR value to screen height and store at end
pulseData[SCREEN_WIDTH - 1] = map(ldrValue, 0, 4095, SCREEN_HEIGHT - 1, SCREEN_HEIGHT / 2);
// Show data on OLED
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
// Text data
display.setCursor(0,0);
display.print("T:"); display.print(temperature); display.print("C ");
display.print("H:"); display.print(humidity); display.println("%");
display.print("O2:"); display.print(oxygenLevel); display.println("%");
display.print("M:"); display.println(motionDetected ? "Yes" : "No");
// Draw pulse waveform
for (int x = 1; x < SCREEN_WIDTH; x++) {
display.drawLine(x - 1, pulseData[x - 1], x, pulseData[x], SSD1306_WHITE);
}
display.display();
// Control stepper motor if oxygen < threshold
if (oxygenLevel < oxygenThreshold) {
stepper.step(100);
}
delay(100); // Faster refresh for smooth graph
}