#define BLYNK_TEMPLATE_ID "TMPL6ANBnCYwI"
#define BLYNK_TEMPLATE_NAME "SMOKE DETECTOR"
#define BLYNK_AUTH_TOKEN "NlgE8WqmDW8m-4qNRxGWPRTuPkeUWGjo"
#define BLYNK_PRINT Serial
#define BLYNK_DEBUG
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Wire.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
BlynkTimer timer;
const int smokeA0 = 18;
int sensorThres = 100;
int data;
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_SDA 21
#define OLED_SCL 22
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
const int buzzerPin = 2;
void displayCenteredText(const String &text, int size) {
int16_t x1;
int16_t y1;
uint16_t width;
uint16_t height;
display.setTextSize(size);
display.getTextBounds(text, 0, 0, &x1, &y1, &width, &height);
display.setCursor((SCREEN_WIDTH - width) / 2, (SCREEN_HEIGHT - height) / 2);
display.println(text);
}
void sendSensor() {
data = analogRead(smokeA0);
Blynk.virtualWrite(V0, data);
display.clearDisplay();
display.setTextColor(WHITE);
if (data > sensorThres) {
Blynk.logEvent("gas_detected", "GAS DETECTED");
display.setCursor(0, 40);
displayCenteredText("ASAP TERDETEKSI", 1);
display.display();
tone(buzzerPin, 3000);
} else {
display.setCursor(0, 40);
displayCenteredText("KUALITAS UDARA", 1);
display.setCursor(0, 20);
displayCenteredText("NORMAL", 1);
display.display();
noTone(buzzerPin);
}
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, pass);
Serial.print("Connecting to WiFi");
int attempt = 0;
while (WiFi.status() != WL_CONNECTED && attempt < 20) {
delay(500);
Serial.print(".");
attempt++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\nConnected to the WiFi network");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("\nFailed to connect to WiFi. Status: " + String(WiFi.status()));
}
Blynk.config(BLYNK_AUTH_TOKEN);
bool result = Blynk.connect();
Serial.println(result ? "Blynk Connected" : "Blynk Not Connected");
pinMode(smokeA0, INPUT);
pinMode(buzzerPin, OUTPUT);
timer.setInterval(2500L, sendSensor);
Wire.begin(OLED_SDA, OLED_SCL);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(1);
display.setCursor(0, 0);
display.println("Initializing...");
display.display();
}
void loop() {
Blynk.run();
timer.run();
}