#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
const int soundSensor1Pin = A1;
const int soundSensor2Pin = A2;
const int lightSensorPin = A0;
const int buzzerPin = 8;
const int soundThreshold = 600;
const int lightThreshold = 500;
unsigned long previousMillis = 0;
const long interval = 200; // Update interval ms
void setup() {
Serial.begin(9600);
lcd.init();
lcd.backlight();
// Print static labels once
lcd.setCursor(0, 0);
lcd.print("Firework Detector");
lcd.setCursor(0, 1);
lcd.print("Sound1: ");
lcd.setCursor(0, 2);
lcd.print("Sound2: ");
lcd.setCursor(0, 3);
lcd.print("Light : ");
pinMode(buzzerPin, OUTPUT);
digitalWrite(buzzerPin, LOW);
}
void printValueAt(int col, int row, int value, int width=6) {
// Print integer value right after label with fixed width for smooth update
char buf[7];
snprintf(buf, sizeof(buf), "%*d", width, value); // right-aligned, width padded
lcd.setCursor(col, row);
lcd.print(buf);
}
void updateFireworkStatus(bool detected) {
lcd.setCursor(15, 3); // fixed position
if (detected) {
lcd.print("FIREWORK");
} else {
lcd.print(" "); // clear old text smoothly
}
}
void loop() {
unsigned long currentMillis = millis();
int sound1 = analogRead(soundSensor1Pin);
int sound2 = analogRead(soundSensor2Pin);
int lightLevel = analogRead(lightSensorPin);
bool fireworkDetected = (sound1 > soundThreshold || sound2 > soundThreshold) && lightLevel > lightThreshold;
// Buzzer control real-time
digitalWrite(buzzerPin, fireworkDetected ? HIGH : LOW);
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// Update sensor values smoothly
printValueAt(8, 1, sound1);
printValueAt(8, 2, sound2);
printValueAt(8, 3, lightLevel);
updateFireworkStatus(fireworkDetected);
}
// Serial command to print sensor values on demand
if (Serial.available() > 0) {
String cmd = Serial.readStringUntil('\n');
cmd.trim();
if (cmd.equalsIgnoreCase("update")) {
Serial.print("Sound1: "); Serial.print(sound1);
Serial.print(" Sound2: "); Serial.print(sound2);
Serial.print(" Light: "); Serial.println(lightLevel);
if (fireworkDetected) Serial.println(">> Firework Detected!");
}
}
}