#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#include <HX711.h>
// Pin definitions
#define DHTPIN 4
#define DHTTYPE DHT22
#define HX711_DT 16
#define HX711_SCK 17
#define DOOR_SENSOR_PIN 5
// Sensor objects
DHT dht(DHTPIN, DHTTYPE);
HX711 scale;
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* serverUrl = "https://smart-fridge-two.vercel.app/api/sensors";
// HX711 Calibration - ADJUST THESE FOR YOUR LOAD CELL
// For 50kg load cell, typical values are between -400 to -7500
float CALIBRATION_FACTOR = 420.0; // Start with this, adjust as needed
// Timing
unsigned long lastSendTime = 0;
const unsigned long sendInterval = 2000;
// Sensor status
bool dht_working = false;
bool hx711_working = false;
// DHT22 retry settings
int dht_fail_count = 0;
const int MAX_DHT_FAILS = 3;
void setup() {
Serial.begin(115200);
delay(2000);
Serial.println("\n\n╔════════════════════════════════════╗");
Serial.println("║ SMART FRIDGE SYSTEM STARTING ║");
Serial.println("╚════════════════════════════════════╝\n");
// Door sensor
pinMode(DOOR_SENSOR_PIN, INPUT_PULLUP);
Serial.println("✓ Door sensor ready (GPIO " + String(DOOR_SENSOR_PIN) + ")");
// DHT22 initialization
Serial.println("\n--- Initializing DHT22 ---");
Serial.println("Pin: GPIO " + String(DHTPIN));
dht.begin();
delay(2500);
for (int i = 0; i < 3; i++) {
float testTemp = dht.readTemperature();
float testHum = dht.readHumidity();
if (!isnan(testTemp) && !isnan(testHum)) {
dht_working = true;
Serial.println("✓ DHT22 WORKING!");
Serial.println(" Temperature: " + String(testTemp, 2) + " °C");
Serial.println(" Humidity: " + String(testHum, 2) + " %");
break;
} else {
Serial.println(" Attempt " + String(i+1) + "/3 failed...");
delay(1000);
}
}
if (!dht_working) {
Serial.println("✗ DHT22 FAILED - Will retry during operation");
}
// HX711 initialization
Serial.println("\n--- Initializing HX711 (50kg Load Cell) ---");
Serial.println("DT Pin: GPIO " + String(HX711_DT));
Serial.println("SCK Pin: GPIO " + String(HX711_SCK));
scale.begin(HX711_DT, HX711_SCK);
delay(1000);
if (scale.wait_ready_timeout(3000)) {
Serial.println("✓ HX711 detected!");
long raw = scale.read_average(10);
Serial.println(" Raw reading: " + String(raw));
if (raw != 0 && abs(raw) > 1000) {
// Set calibration
scale.set_scale(CALIBRATION_FACTOR);
delay(500);
// Tare (zero) the scale
Serial.println(" Taring scale (remove all weight)...");
delay(2000);
scale.tare(20);
delay(500);
float testWeight = scale.get_units(10);
Serial.println(" Test reading: " + String(testWeight, 2) + " kg");
hx711_working = true;
Serial.println("✓ HX711 READY!");
Serial.println(" Calibration factor: " + String(CALIBRATION_FACTOR));
Serial.println(" Note: Adjust CALIBRATION_FACTOR if readings are wrong");
} else {
Serial.println("✗ HX711 invalid reading");
}
} else {
Serial.println("✗ HX711 TIMEOUT");
}
// WiFi connection
Serial.println("\n--- Connecting to WiFi ---");
Serial.println("SSID: " + String(ssid));
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
WiFi.begin(ssid, password);
int wifi_attempts = 0;
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED && wifi_attempts < 40) {
delay(500);
Serial.print(".");
wifi_attempts++;
}
Serial.println();
if (WiFi.status() == WL_CONNECTED) {
Serial.println("✓✓✓ WIFI CONNECTED! ✓✓✓");
Serial.println(" IP: " + WiFi.localIP().toString());
Serial.println(" Signal: " + String(WiFi.RSSI()) + " dBm");
} else {
Serial.println("✗ WiFi FAILED");
}
// Setup summary
Serial.println("\n╔════════════════════════════════════╗");
Serial.println("║ SETUP COMPLETE SUMMARY ║");
Serial.println("╠════════════════════════════════════╣");
Serial.println("║ DHT22: " + String(dht_working ? "✓ WORKING " : "✗ OFFLINE ") + " ║");
Serial.println("║ HX711: " + String(hx711_working ? "✓ WORKING " : "✗ OFFLINE ") + " ║");
Serial.println("║ Door: ✓ WORKING ║");
Serial.println("║ WiFi: " + String(WiFi.status() == WL_CONNECTED ? "✓ CONNECTED" : "✗ OFFLINE ") + " ║");
Serial.println("╚════════════════════════════════════╝\n");
delay(1000);
}
void loop() {
unsigned long currentTime = millis();
if (currentTime - lastSendTime >= sendInterval) {
lastSendTime = currentTime;
Serial.println("┌────────────────────────────────────┐");
Serial.println("│ SENSOR READING CYCLE │");
Serial.println("└────────────────────────────────────┘");
// ===== READ DHT22 WITH RETRY LOGIC =====
float temp = -999;
float humidity = -999;
bool temp_valid = false;
if (dht_working || dht_fail_count < MAX_DHT_FAILS) {
// Try reading twice with delay
for (int attempt = 0; attempt < 2; attempt++) {
temp = dht.readTemperature();
humidity = dht.readHumidity();
if (!isnan(temp) && !isnan(humidity)) {
temp_valid = true;
dht_working = true;
dht_fail_count = 0;
break;
}
if (attempt == 0) {
delay(500); // Wait before retry
}
}
if (!temp_valid) {
dht_fail_count++;
if (dht_fail_count >= MAX_DHT_FAILS) {
dht_working = false;
Serial.println("✗ DHT22 DISCONNECTED (multiple failures)");
} else {
Serial.println("⚠ DHT22 read failed, will retry...");
}
}
}
if (temp_valid) {
Serial.println("Temperature: " + String(temp, 1) + " °C [REAL]");
Serial.println("Humidity: " + String(humidity, 1) + " % [REAL]");
} else {
Serial.println("Temperature: DISCONNECTED ✗");
Serial.println("Humidity: DISCONNECTED ✗");
temp = -999;
humidity = -999;
}
// ===== READ HX711 WITH VALIDATION =====
float weight = -999;
bool weight_valid = false;
if (hx711_working) {
if (scale.wait_ready_timeout(1000)) {
// Get reading with multiple samples
weight = scale.get_units(5);
// Validate reading
if (!isnan(weight)) {
// Filter out noise - values very close to zero
if (abs(weight) < 0.05) {
weight = 0.0;
}
// If weight is negative and more than -0.5, likely calibration issue
// Re-tare if needed
if (weight < -0.5) {
Serial.println("⚠ Negative weight detected, re-taring...");
scale.tare(10);
delay(500);
weight = scale.get_units(5);
if (abs(weight) < 0.05) weight = 0.0;
}
weight_valid = true;
}
} else {
Serial.println("⚠ HX711 timeout");
hx711_working = false;
}
}
if (weight_valid) {
Serial.println("Weight: " + String(weight, 2) + " kg [REAL]");
} else {
Serial.println("Weight: DISCONNECTED ✗");
weight = -999;
}
// ===== READ DOOR SENSOR =====
bool doorOpen = digitalRead(DOOR_SENSOR_PIN) == LOW;
Serial.println("Door: " + String(doorOpen ? "OPEN ⚠️" : "CLOSED ✓"));
// ===== SEND DATA TO SERVER =====
Serial.println();
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.setTimeout(8000);
http.begin(serverUrl);
http.addHeader("Content-Type", "application/json");
// Build JSON
String jsonData = "{";
jsonData += "\"temperature\":" + String(temp, 2) + ",";
jsonData += "\"humidity\":" + String(humidity, 2) + ",";
jsonData += "\"weight\":" + String(weight, 2) + ",";
jsonData += "\"doorOpen\":" + String(doorOpen ? "true" : "false") + ",";
jsonData += "\"pressure\":" + String(weight > 0 ? weight : 0.0, 2) + ",";
jsonData += "\"gasLevel\":0";
jsonData += "}";
Serial.println("→ Sending to server...");
Serial.println(" Data: " + jsonData);
int httpCode = http.POST(jsonData);
if (httpCode == 200) {
Serial.println("✓✓✓ DATA SENT SUCCESSFULLY! ✓✓✓");
String response = http.getString();
Serial.println("Server: " + response);
} else if (httpCode > 0) {
Serial.println("⚠ HTTP Code: " + String(httpCode));
} else {
Serial.println("✗ Send failed: " + http.errorToString(httpCode));
}
http.end();
} else {
Serial.println("✗ WiFi disconnected - reconnecting...");
WiFi.disconnect();
delay(100);
WiFi.begin(ssid, password);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 10) {
delay(500);
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("✓ Reconnected!");
}
}
Serial.println("════════════════════════════════════\n");
}
}