Sunday, 1 November 2026

AI-Based Food Spoilage Detection & Freshness Monitoring System Using ESP32 | IoT, n8n & AI Alerts

FreshGuard AI – AI-Powered IoT Food Spoilage Detection and Smart Alert System Using ESP32, Multi-Sensor Monitoring, n8n Automation, Telegram Voice Alerts, Google Sheets & ThingSpeak

Complete IoT Project Documentation ESP32 + AI + n8n

IoT Based Food Spoilage Detection System using ESP32 | DHT11 | MQ4 | Moisture Sensor | E-Mail Alerts – svskits , svsembedded  , CONTACT: 9491535690, 7842358459
Pacific Food Service - Knet
IoT Based Food Monitoring System

1. Project overview

FreshGuard AI is an intelligent food freshness monitoring and spoilage risk detection system designed to monitor the environmental conditions and gas emissions associated with food deterioration.

The system uses an ESP32 microcontroller connected to multiple sensors to continuously collect food-storage parameters such as:

  • Gas concentration and changes in gas emissions using the MQ-4 sensor.

  • Temperature using the DHT11 sensor.

  • Relative humidity using the DHT11 sensor.

  • Moisture-related measurements using a capacitive moisture sensor.

  • Optional additional measurements using a food-storage temperature probe.

The ESP32 transmits the collected sensor readings through Wi-Fi to an IoT cloud platform and an n8n automation server.

The collected data is processed using a spoilage-risk detection algorithm. An AI Agent can analyze sensor readings, historical trends, and food-specific thresholds to classify the food condition.

When abnormal conditions are detected, the system automatically triggers notifications through:

  1. Telegram text notifications.

  2. Telegram voice/audio alerts.

  3. Gmail email notifications.

  4. Google Sheets automatic data logging.

  5. ThingSpeak cloud analytics.

  6. A real-time IoT web dashboard.

  7. An AI Agent that generates food freshness analysis and recommendations.

The main objective is to develop a low-cost, intelligent, automated food monitoring solution that can help reduce food waste and improve food-storage management.

Proposed project title

FreshGuard AI: An Intelligent IoT-Based Food Spoilage Detection and Freshness Monitoring System Using ESP32, Multi-Sensor Analytics, AI Agents, n8n Automation, and Real-Time Cloud Notifications.

2. Main objectives

  • Develop an ESP32-based food spoilage monitoring prototype.

  • Integrate gas, temperature, humidity, and moisture sensors.

  • Monitor changes in food-storage environmental conditions.

  • Detect abnormal sensor patterns associated with potential food spoilage.

  • Develop an intelligent spoilage-risk classification algorithm.

  • Transmit sensor data to a cloud platform through Wi-Fi.

  • Develop a web-based dashboard for real-time monitoring.

  • Automate notifications using n8n.

  • Generate Telegram voice alerts for critical conditions.

  • Store historical sensor readings in Google Sheets.

  • Visualize sensor readings and trends using ThingSpeak.

  • Implement an AI Agent for interpreting sensor readings and generating recommendations.

3. Complete system architecture

The project consists of five major layers.

FreshGuard AI – System architecture

FOOD STORAGE / MONITORING CHAMBER

Food sample under controlled monitoring

LAYER 1 – MULTI-SENSOR SYSTEM

MQ-4

Gas response

DHT11

Temperature

DHT11

Humidity

Capacitive sensor

Moisture proxy

LAYER 2 – ESP32 MICROCONTROLLER

Sensor acquisition • Data processing • Wi-Fi communication • Initial risk calculation

LAYER 3 – IoT CLOUD & n8n AUTOMATION

Webhook • Data processing • AI Agent • Workflow execution

LAYER 4 – CLOUD STORAGE & ANALYTICS

ThingSpeak

Live sensor charts

Google Sheets

Historical records

LAYER 5 – SMART NOTIFICATION SYSTEM

Telegram

Text alerts

Voice alerts

Audio messages

Gmail

Email reports

Web dashboard

Live monitoring

4. Hardware components required

Component

Quantity

Purpose

ESP32 DevKit V1

1

Main controller

MQ-4 gas sensor module

1

Detect methane-related gas response

DHT11 sensor

1

Temperature and humidity

Capacitive moisture sensor

1

Moisture-related measurement

Breadboard

1

Prototype connections

Jumper wires

As required

Connections

5V regulated supply

1

MQ-4 and system power

USB cable

1

ESP32 programming

Food-storage enclosure

1

Sensor monitoring chamber

Optional OLED display

1

Local display

Optional DS18B20

1

More suitable temperature measurement

Important sensor limitation: MQ-4 is primarily a methane-sensitive gas sensor. It is not a dedicated food-spoilage detector and does not identify specific spoilage compounds. DHT11 measures ambient temperature and humidity, not the internal temperature or microbiological condition of food. The capacitive moisture sensor is also only a proxy and must be selected and calibrated for the actual application.

For a more advanced version, consider adding a BME680/BME688 or a suitable VOC sensor, depending on the target food and validation requirements.

5. ESP32 pin configuration

The following pin configuration is recommended for the prototype.

Sensor/component

ESP32 pin

Connection

MQ-4 analog output

GPIO 34

ADC input

DHT11 DATA

GPIO 4

Digital input

Moisture sensor AO

GPIO 35

ADC input

MQ-4 VCC

External 5V

Power

DHT11 VCC

3.3V

Power

Moisture sensor VCC

3.3V

Power

All sensor GND

GND

Common ground

Pin connection diagram

Important MQ-4 electrical connection

The MQ-4 module generally operates from 5V. Its analog output may exceed the ESP32's 3.3V ADC input limit.

Use a voltage divider:

  • MQ-4 AO → 10 kΩ resistor → ESP32 GPIO34.

  • GPIO34 → 20 kΩ resistor → GND.

  • MQ-4 GND → ESP32 GND.

  • MQ-4 VCC → regulated 5V.

This divider reduces a 5V signal to approximately 3.33V. Verify the actual module's output voltage before connecting it.

The MQ-4 heater also consumes significant current. Do not power it from an ESP32 GPIO pin.

6. Schematic diagram

Text-based wiring schematic

text
                 +----------------------+
                 |      ESP32 DEVKIT    |
                 |                      |
                 | GPIO34 <--- MQ-4 AO  |
                 | GPIO4  <--- DHT11 DATA
                 | GPIO35 <--- Moisture AO
                 |                      |
                 | 3.3V ---- DHT11 VCC  |
                 | 3.3V ---- Moisture VCC
                 | GND ----- COMMON GND |
                 +----------------------+
                           |
                     Wi-Fi Network
                           |
                      Internet
                           |
                      n8n Server

MQ-4 POWER:
External regulated 5V ---> MQ-4 VCC
External GND ------------> MQ-4 GND
MQ-4 AO ---> Voltage divider ---> GPIO34

Construction advice: Place the electronics outside the food container whenever possible. Route only appropriate sensor probes into the monitoring chamber. Keep the MQ-4 module away from condensation and food contact. Never place mains-powered or unprotected electronics inside a food-storage environment.

7. Working principle of FreshGuard AI

The system works in the following sequence.

  1. The ESP32 starts and connects to the Wi-Fi network.

  2. The sensors begin collecting environmental measurements.

  3. The MQ-4 sensor measures its analog gas response.

  4. The DHT11 collects temperature and humidity.

  5. The moisture sensor provides an analog moisture-related measurement.

  6. The ESP32 filters and packages the sensor readings.

  7. The ESP32 calculates an initial spoilage-risk score.

  8. The readings are transmitted to the n8n webhook.

  9. n8n receives and processes the incoming JSON data.

  10. The AI Agent analyzes the readings and historical information.

  11. The system classifies the condition as Normal, Warning, or Critical.

  12. Sensor readings are stored in Google Sheets.

  13. ThingSpeak receives sensor readings for graphical analytics.

  14. Telegram sends a text notification when required.

  15. The voice-alert workflow generates an audio notification for critical events.

  16. Gmail sends an automated email report.

  17. The dashboard displays the latest food-storage condition.

8. System flowchart

mermaid

flowchart TD
    A([System Start]) --> B[Initialize ESP32]
    B --> C[Connect to Wi-Fi]
    C --> D[Initialize Sensors]
    D --> E[Read MQ-4 Gas Sensor]
    E --> F[Read Temperature and Humidity]
    F --> G[Read Moisture Sensor]
    G --> H[Filter Sensor Readings]
    H --> I[Calculate Spoilage Risk Score]
    I --> J[Send Data to n8n Webhook]
    J --> K[Store Data in Google Sheets]
    J --> L[Update ThingSpeak]
    J --> M[AI Agent Analysis]
    M --> N{Spoilage Risk}
    N -->|Normal| O[Normal Status]
    N -->|Warning| P[Telegram Warning]
    N -->|Critical| Q[Telegram Text and Voice]
    Q --> R[Send Gmail Alert]
    O --> S[Update Dashboard]
    P --> S
    R --> S
    S --> T[Wait for Next Reading]
    T --> E

9. AI-based food spoilage detection algorithm

This is one of the most important parts of the project.

The ESP32 measures physical parameters, but the AI component should analyze the relationship between those parameters and food deterioration.

9.1 Sensor input parameters

Let:

  • GG = MQ-4 analog sensor response.

  • TT = Temperature in °C.

  • HH = Relative humidity in percentage.

  • MM = Moisture sensor reading.

  • GbG_b = Baseline gas response for the selected food.

  • TrT_r = Reference temperature.

  • HrH_r = Reference humidity.

9.2 Risk score calculation

For the initial prototype, implement a rule-based score:

R=0.40Gs+0.25Ts+0.20Hs+0.15MsR = 0.40G_s+0.25T_s+0.20H_s+0.15M_s

Where:

  • GsG_s = normalized gas anomaly score.

  • TsT_s = normalized temperature risk.

  • HsH_s = normalized humidity risk.

  • MsM_s = normalized moisture anomaly score.

Each parameter is normalized between 0 and 100.

The weights are example engineering values, not scientifically validated spoilage predictors. They must be calibrated against actual observations for each food type.

9.3 Food freshness classification

Risk score

Classification

Suggested action

0–29

Normal

Continue monitoring

30–59

Warning

Inspect storage conditions

60–100

Critical

Inspect food and follow food-safety procedures

Example spoilage-risk visualization

Normal

0–29

Warning

30–59

Critical

60–100

Illustrative software classification, not validated food-safety limits.

9.4 How to implement real AI

To make the project genuinely AI-based rather than only threshold-based, collect a labeled dataset.

Example dataset structure:

Gas response

Temperature

Humidity

Moisture

Label

320

8

55

300

Fresh

410

12

62

350

Fresh

650

20

72

500

Early deterioration

820

27

80

650

Suspected deterioration

These are illustrative numbers, not measured experimental data.

Recommended AI development process:

  1. Collect readings from fresh food samples.

  2. Collect readings during controlled storage and deterioration.

  3. Record the actual food type, storage time and temperature.

  4. Label observations using an independently established reference method.

  5. Create a CSV dataset.

  6. Clean and normalize the data.

  7. Train a Random Forest or XGBoost classifier.

  8. Evaluate accuracy, precision, recall and confusion matrix.

  9. Deploy the trained model through an API or compatible edge model.

  10. Let the n8n AI Agent explain the results in natural language.

Important: A language-model AI Agent should not independently decide that food is safe to eat. It can interpret validated model outputs and explain them. Spoilage detection must be experimentally validated for the particular food type. Gas readings alone cannot establish microbiological safety.

10. ESP32 Arduino IDE software installation

Required software

Software

Purpose

Arduino IDE

ESP32 programming

ESP32 board package

Microcontroller support

DHT sensor library

DHT11 readings

Adafruit Unified Sensor

Sensor dependency

ThingSpeak

Cloud analytics

n8n

Automation

Google Sheets

Data storage

Telegram Bot API

Notifications

Arduino IDE setup

  1. Install Arduino IDE.

  2. Open Preferences.

  3. Add the ESP32 board manager URL:

https://espressif.github.io/arduino-esp32/package_esp32_index.json

  1. Open Boards Manager.

  2. Search for ESP32.

  3. Install the Espressif ESP32 package.

  4. Select ESP32 Dev Module.

  5. Install the following libraries through Library Manager:

    • DHT sensor library by Adafruit.

    • Adafruit Unified Sensor.

  6. Connect ESP32 through USB.

  7. Select the correct COM port.

11. Complete ESP32 Arduino source code

This first working version performs sensor acquisition, basic anomaly scoring, Wi-Fi transmission, and ThingSpeak cloud updates.

It sends a JSON object to n8n, where the advanced AI analysis and notifications can be performed.

Before uploading, change the Wi-Fi credentials, webhook URL, and ThingSpeak API key.

cpp

#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#include <math.h>

// ---------------- WIFI SETTINGS ----------------

const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";

// ---------------- N8N WEBHOOK ----------------

const char* N8N_WEBHOOK =
"https://YOUR_N8N_DOMAIN/webhook/freshguard";

// ---------------- THINGSPEAK ----------------

const char* THINGSPEAK_KEY =
"YOUR_THINGSPEAK_WRITE_API_KEY";

const char* THINGSPEAK_URL =
"https://api.thingspeak.com/update";

// ---------------- SENSOR PINS ----------------

#define MQ4_PIN 34
#define DHT_PIN 4
#define MOISTURE_PIN 35

#define DHT_TYPE DHT11

DHT dht(DHT_PIN, DHT_TYPE);

// ---------------- SETTINGS ----------------

const unsigned long INTERVAL = 60000;

unsigned long lastUpdate = 0;

float gasBaseline = 0;
bool baselineReady = false;

// Example calibration values.
// Replace using actual measurements.
const int MOISTURE_DRY = 3000;
const int MOISTURE_WET = 1200;

// ---------------- WIFI CONNECTION ----------------

void connectWiFi() {

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  Serial.print("Connecting to WiFi");

  unsigned long start = millis();

  while (WiFi.status() != WL_CONNECTED &&
         millis() - start < 20000) {

    delay(500);
    Serial.print(".");
  }

  Serial.println();

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("WiFi Connected");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("WiFi connection failed");
  }
}

// ---------------- SENSOR FILTER ----------------

int readAverage(int pin) {

  long total = 0;

  for (int i = 0; i < 10; i++) {
    total += analogRead(pin);
    delay(20);
  }

  return total / 10;
}

// ---------------- RISK CALCULATION ----------------

float calculateRisk(
  float gas,
  float temp,
  float humidity,
  float moisture
) {

  // Relative gas change from the baseline.
  float gasScore = 0;

  if (baselineReady && gasBaseline > 0) {

    float change =
      ((gas - gasBaseline) / gasBaseline) * 100.0;

    gasScore = constrain(change, 0, 100);
  }

  // Example environmental anomaly scores.
  float tempScore =
    constrain((temp - 10.0) * 5.0, 0, 100);

  float humidityScore =
    constrain((humidity - 50.0) * 2.0, 0, 100);

  // Moisture anomaly is an example only.
  float moistureScore =
    constrain(moisture, 0, 100);

  float risk =
    (0.40 * gasScore) +
    (0.25 * tempScore) +
    (0.20 * humidityScore) +
    (0.15 * moistureScore);

  return constrain(risk, 0, 100);
}

// ---------------- CLASSIFICATION ----------------

String getStatus(float risk) {

  if (risk < 30) {
    return "NORMAL";
  }

  if (risk < 60) {
    return "WARNING";
  }

  return "CRITICAL";
}

// ---------------- SEND TO N8N ----------------

void sendToN8N(
  int gas,
  float temp,
  float humidity,
  int moisture,
  float risk,
  String status
) {

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi unavailable");
    return;
  }

  HTTPClient http;

  http.begin(N8N_WEBHOOK);
  http.addHeader("Content-Type", "application/json");

  String json = "{";

  json += "\"device\":\"FreshGuard-ESP32\",";
  json += "\"gas_raw\":" + String(gas) + ",";
  json += "\"temperature\":" + String(temp, 1) + ",";
  json += "\"humidity\":" + String(humidity, 1) + ",";
  json += "\"moisture_raw\":" + String(moisture) + ",";
  json += "\"risk_score\":" + String(risk, 1) + ",";
  json += "\"status\":\"" + status + "\"";

  json += "}";

  Serial.println("Sending to n8n:");
  Serial.println(json);

  int responseCode = http.POST(json);

  Serial.print("n8n Response: ");
  Serial.println(responseCode);

  http.end();
}

// ---------------- THINGSPEAK UPDATE ----------------

void sendToThingSpeak(
  int gas,
  float temp,
  float humidity,
  int moisture,
  float risk
) {

  if (WiFi.status() != WL_CONNECTED) {
    return;
  }

  HTTPClient http;

  String url = String(THINGSPEAK_URL);

  url += "?api_key=" + String(THINGSPEAK_KEY);
  url += "&field1=" + String(gas);
  url += "&field2=" + String(temp, 1);
  url += "&field3=" + String(humidity, 1);
  url += "&field4=" + String(moisture);
  url += "&field5=" + String(risk, 1);

  http.begin(url);

  int responseCode = http.GET();

  Serial.print("ThingSpeak Response: ");
  Serial.println(responseCode);

  http.end();
}

// ---------------- SETUP ----------------

void setup() {

  Serial.begin(115200);

  analogReadResolution(12);

  dht.begin();

  pinMode(MQ4_PIN, INPUT);
  pinMode(MOISTURE_PIN, INPUT);

  connectWiFi();

  Serial.println("FreshGuard AI Started");

  // MQ-4 requires proper initial conditioning.
  // Follow the manufacturer's warm-up instructions.
}

// ---------------- MAIN LOOP ----------------

void loop() {

  if (millis() - lastUpdate >= INTERVAL) {

    lastUpdate = millis();

    int gas = readAverage(MQ4_PIN);

    int moistureRaw =
      readAverage(MOISTURE_PIN);

    float temp = dht.readTemperature();
    float humidity = dht.readHumidity();

    if (isnan(temp) || isnan(humidity)) {
      Serial.println("DHT11 reading failed");
      return;
    }

    // Convert raw sensor value to a relative
    // 0-100 moisture proxy.
    float moisture = constrain(
      ((float)(MOISTURE_DRY - moistureRaw) /
      (MOISTURE_DRY - MOISTURE_WET)) * 100.0,
      0, 100
    );

    // Establish initial gas baseline.
    if (!baselineReady) {

      gasBaseline = gas;
      baselineReady = true;

      Serial.println("Gas baseline initialized");
    }

    float risk = calculateRisk(
      gas,
      temp,
      humidity,
      moisture
    );

    String status = getStatus(risk);

    Serial.println("-------------------------");
    Serial.println("FRESHGUARD AI SENSOR DATA");

    Serial.print("Gas raw: ");
    Serial.println(gas);

    Serial.print("Temperature: ");
    Serial.println(temp);

    Serial.print("Humidity: ");
    Serial.println(humidity);

    Serial.print("Moisture proxy: ");
    Serial.println(moisture);

    Serial.print("Risk score: ");
    Serial.println(risk);

    Serial.print("Status: ");
    Serial.println(status);

    sendToN8N(
      gas,
      temp,
      humidity,
      moistureRaw,
      risk,
      status
    );

    sendToThingSpeak(
      gas,
      temp,
      humidity,
      moistureRaw,
      risk
    );
  }

  // Reconnect if Wi-Fi disconnects.
  if (WiFi.status() != WL_CONNECTED) {
    connectWiFi();
  }
}

Understanding the code

  • connectWiFi() connects the ESP32 to the wireless network.

  • readAverage() averages sensor measurements to reduce short-term noise.

  • calculateRisk() calculates the initial prototype risk score.

  • getStatus() assigns a status based on the score.

  • sendToN8N() sends sensor readings to the automation server.

  • sendToThingSpeak() updates the cloud analytics channel.

  • loop() executes the sensor acquisition and transmission cycle.

Calibration requirement: The initial gas baseline must be collected under stable conditions. A single startup measurement is not sufficient for a dependable system. In the production version, collect a rolling baseline, account for sensor warm-up and drift, and use food-specific calibrated reference data. The example scoring function is a demonstration algorithm, not a validated spoilage model.

12. n8n automation – Complete workflow design

n8n is the automation engine of FreshGuard AI.

It receives sensor data from the ESP32 and automatically executes the required cloud, AI, and notification tasks.

12.1 Main n8n workflow

mermaid

flowchart TD
    A[ESP32 HTTP POST] --> B[Webhook Trigger]
    B --> C[Validate JSON Data]
    C --> D[Edit Fields / Normalize]
    D --> E[Google Sheets Append Row]
    D --> F[ThingSpeak Update]
    D --> G[Risk Classification]
    G --> H[AI Agent]
    H --> I{Status}
    I -->|NORMAL| J[Dashboard Update]
    I -->|WARNING| K[Telegram Warning]
    I -->|CRITICAL| L[Telegram Alert]
    L --> M[AI Alert Message]
    M --> N[Text-to-Speech Service]
    N --> O[Telegram Audio]
    L --> P[Gmail Alert]
    K --> P
    J --> Q[Workflow Complete]
    O --> Q
    P --> Q

12.2 Node-by-node configuration

Node

n8n node type

Function

1

Webhook

Receive ESP32 JSON

2

IF

Validate incoming values

3

Edit Fields

Organize sensor data

4

Google Sheets

Save readings

5

HTTP Request

Update ThingSpeak

6

Code

Calculate risk category

7

AI Agent

Analyze food freshness data

8

Switch

Route by risk category

9

Telegram

Send text alert

10

HTTP Request

Generate voice audio

11

Telegram

Send audio alert

12

Gmail

Send email report

13. Creating the n8n workflow step by step

Step 1: Install or access n8n

You can use:

  • n8n Cloud.

  • Self-hosted n8n.

  • A VPS-based n8n installation.

For a student prototype, n8n Cloud is generally the easiest starting point.

Step 2: Create a webhook

  1. Open the n8n editor.

  2. Create a new workflow.

  3. Add a Webhook node.

  4. Set HTTP Method to POST.

  5. Set the path to:

text
freshguard
  1. Select JSON as the expected input format where applicable.

  2. Save the workflow.

  3. Activate the workflow before using its production URL.

The resulting URL should have this general structure:

text
https://your-n8n-domain/webhook/freshguard

Use the production URL in the ESP32 source code.

Step 3: Receive sensor data

The ESP32 sends:

json
{
  "device": "FreshGuard-ESP32",
  "gas_raw": 650,
  "temperature": 25.5,
  "humidity": 72.0,
  "moisture_raw": 1800,
  "risk_score": 58.5,
  "status": "WARNING"
}

The actual numbers above are sample values.

Step 4: Add an Edit Fields node

Create these fields:

Field

Input

Device

device

Gas

gas_raw

Temperature

temperature

Humidity

humidity

Moisture

moisture_raw

Risk score

risk_score

Status

status

Timestamp

Current timestamp

This creates a standardized data structure for the rest of the workflow.

Step 5: Add a Code node for risk classification

Use this JavaScript:

javascript

const data = $input.first().json;

const risk = Number(data.risk_score);

let status = "NORMAL";
let recommendation = "Continue monitoring.";

if (risk >= 60) {
  status = "CRITICAL";
  recommendation =
    "Inspect the food and storage conditions immediately.";
} else if (risk >= 30) {
  status = "WARNING";
  recommendation =
    "Check environmental conditions and inspect the food.";
}

return [{
  json: {
    ...data,
    risk_score: risk,
    status,
    recommendation,
    processed_at: new Date().toISOString()
  }
}];

Step 6: Add Google Sheets integration

Create a Google spreadsheet named:

FreshGuard_AI_Database

Create a sheet called:

Sensor_Records

Use these columns:

Column

Description

Timestamp

Date and time

Device_ID

ESP32 identification

Gas_Raw

MQ-4 reading

Temperature

Temperature

Humidity

Humidity

Moisture_Raw

Moisture reading

Risk_Score

Calculated score

Status

Normal/Warning/Critical

Recommendation

AI or rule-based output

In n8n:

  1. Add Google Sheets node.

  2. Connect your Google account.

  3. Select Append Row.

  4. Select the spreadsheet.

  5. Select the worksheet.

  6. Map each incoming JSON field to the appropriate column.

Now each ESP32 reading is stored automatically.

Step 7: Add ThingSpeak integration

Create a ThingSpeak channel called FreshGuard AI.

Configure the following fields:

ThingSpeak field

Parameter

Field 1

Gas response

Field 2

Temperature

Field 3

Humidity

Field 4

Moisture

Field 5

Risk score

The ESP32 code already contains a direct ThingSpeak update function.

Alternatively, let n8n handle this using an HTTP Request node.

ThingSpeak is useful for historical trends and sensor graphs. The actual dashboard webpage can display these charts using the ThingSpeak visualization/embed features.

14. AI Agent integration in n8n

This is where FreshGuard AI becomes more intelligent.

An AI Agent can analyze:

  • Current sensor readings.

  • Historical gas trends.

  • Environmental changes.

  • Food type.

  • Storage conditions.

  • Validated machine-learning classification.

  • Previous warning events.

Suggested AI Agent system prompt

Use the following as the starting system instruction for your n8n AI Agent.

text

You are FreshGuard AI, an intelligent food-storage
monitoring assistant.

Your responsibility is to analyze sensor data
and explain potential food deterioration risks.

INPUT PARAMETERS:
- Food type
- MQ-4 gas sensor reading
- Temperature
- Relative humidity
- Moisture sensor reading
- Validated ML risk score
- Historical sensor trends

TASKS:

1. Analyze the incoming sensor readings.
2. Identify unusual changes in gas response.
3. Evaluate temperature and humidity conditions.
4. Compare current readings with the validated
   food-specific reference profile.
5. Interpret the supplied ML risk score.
6. Classify the result as NORMAL, WARNING,
   or CRITICAL.
7. Generate a short explanation.
8. Suggest an appropriate inspection action.
9. Generate a concise Telegram notification.
10. Generate a short voice-alert script.

OUTPUT FORMAT:

Food Type:
Risk Level:
Risk Score:
Sensor Analysis:
Potential Concern:
Recommended Action:
Telegram Message:
Voice Alert:

IMPORTANT SAFETY RULES:

- Never claim that gas readings prove food is safe.
- Never diagnose microbiological contamination.
- Never invent missing sensor values.
- Clearly identify uncertain readings.
- MQ-4 is a methane-sensitive sensor,
  not a specific food-spoilage detector.
- Do not recommend eating food based only
  on sensor readings.
- Base conclusions on validated
  food-specific reference data.

Example AI Agent output

FreshGuard AI Analysis

WARNING

58.5 / 100

Illustrative test reading

  • Gas response: Increased relative to baseline.

  • Temperature: 25.5°C.

  • Humidity: 72%.

  • Moisture sensor: Raw value 1800. AI interpretation

The gas response and storage conditions show an abnormal pattern relative to the configured example baseline. Further inspection is recommended.

Recommended action: Check the storage temperature, inspect the food, and compare readings against the validated reference profile.

15. Telegram text notification system

Telegram provides an easy way to receive remote food-monitoring alerts.

Step 1: Create a Telegram bot

  1. Open Telegram.

  2. Search for @BotFather.

  3. Start the BotFather conversation.

  4. Send /newbot.

  5. Enter a bot name.

  6. Choose a username ending in bot.

  7. Copy the generated bot token.

  8. Start a conversation with your new bot.

  9. Retrieve your chat ID using the Telegram Bot API or a suitable n8n Telegram integration.

Keep the bot token private.

Step 2: Connect Telegram to n8n

  1. Add a Telegram node.

  2. Create Telegram credentials.

  3. Enter the bot token.

  4. Choose Send Message.

  5. Configure the chat ID.

  6. Add the message content.

Example Telegram message

FreshGuard AI Bot

Example alert

Food storage warning

FRESHGUARD AI – WARNING

Food Monitoring System detected unusual sensor conditions.

  • Gas response: 650

  • Temperature: 25.5°C

  • Humidity: 72%

  • Risk score: 58.5/100

Recommendation: Inspect the food and verify storage conditions.

Device: FreshGuard-ESP32

Example Telegram message expression:

text
🚨 FRESHGUARD AI ALERT

Food Status: {{$json.status}}

Gas: {{$json.gas_raw}}
Temperature: {{$json.temperature}} °C
Humidity: {{$json.humidity}} %

Risk Score: {{$json.risk_score}}/100

Recommendation:
{{$json.recommendation}}

16. Telegram AI voice notification

Advanced feature

This feature allows the system to send an audio alert rather than only a text message.

Working principle

  1. ESP32 detects abnormal sensor conditions.

  2. ESP32 transmits data to n8n.

  3. n8n calculates the risk category.

  4. The AI Agent generates a short voice script.

  5. A Text-to-Speech (TTS) service converts the script into audio.

  6. n8n receives the generated audio file.

  7. The Telegram node or Telegram Bot API sends the audio to the user.

Voice notification flowchart

mermaid

flowchart TD
    A[ESP32 Sensor Data] --> B[n8n Webhook]
    B --> C[Risk Classification]
    C --> D{Critical Condition?}
    D -->|No| E[Normal Workflow]
    D -->|Yes| F[AI Agent]
    F --> G[Generate Voice Script]
    G --> H[Text-to-Speech API]
    H --> I[Generate MP3 Audio]
    I --> J[Telegram Send Audio]
    J --> K[User Receives Voice Alert]

Example voice script

FreshGuard AI – Voice Alert

"Attention! FreshGuard AI has detected abnormal food-storage sensor readings. The current risk classification is critical. Please inspect the food sample and check the storage conditions immediately. This alert does not confirm that the food is spoiled."

n8n configuration

Add the following nodes:

  1. AI Agent – generate voice text.

  2. HTTP Request – call a TTS service.

  3. Extract or retrieve the generated MP3 binary file.

  4. Telegram – Send Audio.

  5. Select the generated audio file as the binary input.

Suitable TTS options include Google Cloud Text-to-Speech and other compatible speech-generation APIs.

Use MP3 with Telegram's Send Audio operation. If using Telegram's Send Voice operation, use a supported voice-message audio format such as OGG/Opus.

17. Gmail automatic email notifications

Gmail provides a detailed record of important monitoring events.

n8n setup

  1. Add Gmail node.

  2. Authenticate your Google account.

  3. Select Send Message.

  4. Enter the recipient email address.

  5. Configure the subject.

  6. Map the sensor readings into the email body.

  7. Connect the node to the Warning/Critical branch.

Example email

Email
Subject
FreshGuard AI – Food Storage Monitoring Alert

Hello,

FreshGuard AI has detected an abnormal food-storage condition.

Monitoring Information:

  • Device: FreshGuard-ESP32
  • Gas response: 650
  • Temperature: 25.5°C
  • Relative humidity: 72%
  • Risk score: 58.5/100
  • Classification: WARNING

System Analysis

The sensor readings show an unusual pattern relative to the configured monitoring baseline.

Recommended Action

Please inspect the food sample and verify the storage conditions. Sensor readings alone cannot establish food safety or confirm spoilage.

This is an automatically generated monitoring report from FreshGuard AI.

Regards,
FreshGuard AI – Intelligent Food Monitoring System

18. Real-time IoT web dashboard

The web dashboard is the user-facing interface of FreshGuard AI.

It should display the current condition of the monitored food and provide historical sensor analytics.

FrigoSense: Unlock Your Fridge's Secrets. Embrace True Freshness.
PostHarvest Technologies
FoodDocs + ConnectedFresh

Recommended dashboard features

Dashboard component

Function

Current food status

Normal, Warning, Critical

Gas sensor chart

MQ-4 response trend

Temperature chart

Temperature changes

Humidity chart

Relative humidity changes

Moisture chart

Moisture-related readings

Risk score gauge

0–100 risk score

Historical analytics

Daily/weekly trends

Alert history

Previous warning events

Device status

ESP32 online/offline

AI analysis

Latest AI interpretation

Dashboard layout example

FreshGuard AI Dashboard

Demo layout

Temperature

25.5°C

Humidity

72%

Gas response

650

Risk score

58.5

Food monitoring condition

WARNING

Inspect sample
Chart

Illustrative sensor history, not live measurements.

Expand chart
  Gas response Risk score
10:00 320 12
10:10 360 18
10:20 420 25
10:30 510 35
10:40 650 58.5
Illustrative dashboard data. Live values will come from your ESP32 and cloud connection.

Recommended website technologies

  • HTML – dashboard structure.

  • CSS – interface design.

  • JavaScript – live sensor updates.

  • ThingSpeak – sensor analytics.

  • n8n Webhook – backend integration.

  • Google Sheets – historical records.

A useful extension is to build a separate web dashboard that reads data through a secured backend endpoint instead of exposing ThingSpeak or device credentials in frontend JavaScript.

19. Google Sheets data logging and analytics

Google Sheets acts as the historical database for FreshGuard AI.

Every sensor reading received from the ESP32 is automatically stored.

Example Google Sheets records

Time

Gas

Temp °C

Humidity

Risk

Status

10:00

320

8

55

12

Normal

10:10

360

12

62

18

Normal

10:20

420

18

68

25

Normal

10:30

510

22

75

35

Warning

10:40

650

25.5

72

58.5

Warning

Example data for demonstration only.

Benefits

  • Stores historical food-monitoring data.

  • Provides a record of sensor measurements.

  • Helps analyze food-storage trends.

  • Supports the creation of AI training datasets.

  • Makes it easier to prepare project reports.

  • Allows monitoring records to be downloaded as CSV or Excel.

20. Complete end-to-end project workflow

mermaid

flowchart TD
    A([Start FreshGuard AI]) --> B[Power ON ESP32]
    B --> C[Connect Wi-Fi]
    C --> D[Initialize Sensors]
    D --> E[Collect Sensor Data]
    E --> F[Filter and Normalize]
    F --> G[Calculate Initial Risk]
    G --> H[Send JSON to n8n]
    H --> I[Validate Incoming Data]
    I --> J[Save Google Sheets]
    I --> K[Update ThingSpeak]
    I --> L[AI and ML Analysis]
    L --> M[Determine Food Condition]
    M --> N{Risk Level}
    N -->|Normal| O[Continue Monitoring]
    N -->|Warning| P[Telegram Warning]
    N -->|Critical| Q[Telegram Critical Alert]
    Q --> R[Generate AI Voice]
    R --> S[Send Telegram Audio]
    Q --> T[Send Gmail]
    P --> U[Update Dashboard]
    O --> U
    S --> U
    T --> U
    U --> V[Wait 60 Seconds]
    V --> E

21. Hardware and software implementation procedure

Follow these stages to build the complete prototype.

Project implementation checklist

Implementation progress

0/24

Stage 1 – Hardware setup

Stage 2 – ESP32 programming

Stage 3 – Cloud integration

Stage 4 – Automation

Stage 5 – AI and dashboard

22. Testing and expected results

After assembling the prototype, perform the following tests.

Test

Action

Expected result

1

Power on ESP32

ESP32 initializes

2

Connect Wi-Fi

IP address displayed

3

Read MQ-4

Analog gas response displayed

4

Read DHT11

Temperature and humidity displayed

5

Read moisture sensor

Analog reading displayed

6

Send JSON

n8n receives data

7

Update ThingSpeak

Charts receive new values

8

Trigger Warning

Telegram warning received

9

Trigger Critical

Telegram text and audio received

10

Trigger Gmail

Email report delivered

11

Record sensor values

Google Sheets updated

12

Open dashboard

Sensor trends displayed

Expected Serial Monitor output

text
FreshGuard AI Started

WiFi Connected

IP Address: 192.168.1.100

Gas baseline initialized

-------------------------
FRESHGUARD AI SENSOR DATA

Gas raw: 650
Temperature: 25.5
Humidity: 72.0
Moisture proxy: 60.0

Risk score: 58.5
Status: WARNING

Sending to n8n:
{"device":"FreshGuard-ESP32",
"gas_raw":650,
"temperature":25.5,
"humidity":72.0,
"moisture_raw":1800,
"risk_score":58.5,
"status":"WARNING"}

n8n Response: 200
ThingSpeak Response: 200

These are illustrative expected values, not actual hardware measurements.

23. Suggested project folder structure

Organize your final project files as follows:

text
FreshGuard_AI/
│
├── Hardware/
│   ├── Circuit_Diagram.png
│   ├── ESP32_Pin_Configuration.png
│   └── Component_List.xlsx
│
├── ESP32_Firmware/
│   └── FreshGuard_ESP32.ino
│
├── AI_Model/
│   ├── Dataset.csv
│   ├── Data_Preprocessing.py
│   ├── Train_Model.py
│   └── Model_Evaluation.py
│
├── n8n_Automation/
│   ├── Main_Workflow.json
│   ├── Telegram_Alert.json
│   └── Voice_Notification.json
│
├── Web_Dashboard/
│   ├── index.html
│   ├── style.css
│   └── script.js
│
├── Documentation/
│   ├── Abstract.docx
│   ├── Project_Report.docx
│   ├── Flowchart.png
│   ├── Results.docx
│   └── Presentation.pptx
│
└── README.md

24. Limitations and improvements

For a technically credible final-year project, explain the following limitations in your documentation.

Current limitation

Proposed improvement

MQ-4 detects methane-related gas response

Add food-appropriate VOC sensing

DHT11 has limited accuracy

Use calibrated temperature/humidity sensors

Fixed risk thresholds

Train food-specific ML models

Startup gas baseline can drift

Implement rolling calibration

Moisture readings depend on placement

Use application-specific moisture measurement

Wi-Fi dependency

Add offline data storage

Basic web dashboard

Add authenticated real-time dashboard

AI Agent can produce uncertain explanations

Ground it in validated model outputs

Additional advanced features

You can extend FreshGuard AI with:

  • Multiple ESP32 monitoring stations.

  • Different food categories such as fruits, vegetables, dairy and meat.

  • Individual food-specific AI models.

  • QR-code-based food identification.

  • Predictive freshness trend analysis.

  • Historical food-storage reports.

  • Offline alerts using a buzzer.

  • OLED display for local readings.

  • Mobile-friendly dashboard.

  • Battery-powered monitoring.

  • Device fault detection and sensor-disconnection alerts.

  • Automatic sensor calibration reminders.

A particularly useful improvement is to introduce a food-selection option. The system would load a different validated reference profile for each food category instead of applying the same risk thresholds to every food.

25. Project applications

FreshGuard AI can be developed for:

  1. Smart refrigerators: Monitor storage conditions and unusual changes in gas response.

  2. Food warehouses: Monitor environmental conditions in storage areas.

  3. Supermarkets: Monitor food-storage environments.

  4. Restaurants: Record temperature and humidity conditions in storage facilities.

  5. Agricultural storage: Monitor environmental conditions around stored produce.

  6. Food transportation: Monitor storage conditions during transport.

  7. Research laboratories: Study gas-response and environmental trends during controlled food deterioration experiments.

The prototype is a monitoring and research tool, not a certified food-safety inspection system.

26. Suggested final-year project report structure

You can organize your complete academic documentation into these chapters.

Chapter

Title

Contents

1

Introduction

Background, problem statement, objectives

2

Literature Review

Existing spoilage detection methods and IoT systems

3

Proposed System

FreshGuard AI architecture and methodology

4

Hardware Design

ESP32, sensors, components and schematic

5

Software Design

Arduino IDE, firmware and communication

6

AI Implementation

Dataset, preprocessing, ML and classification

7

IoT and Automation

n8n, ThingSpeak and Google Sheets

8

Notification System

Telegram, voice alerts and Gmail

9

Web Dashboard

Interface, cloud analytics and visualizations

10

Testing and Results

Experimental measurements and evaluation

11

Conclusion

Outcomes, limitations and future improvements

27. Project abstract

Writing
 

ABSTRACT

Food spoilage is a major challenge in food storage, transportation, retail, and household environments. Conventional food-quality monitoring methods often depend on manual inspection, which can be time-consuming and may not provide continuous environmental monitoring. To address this challenge, this project proposes FreshGuard AI, an intelligent IoT-based food spoilage risk detection and freshness monitoring system using ESP32, multi-sensor monitoring, AI analytics, and n8n automation.

The proposed system uses an ESP32 microcontroller integrated with an MQ-4 gas sensor, DHT11 temperature and humidity sensor, and a capacitive moisture sensor to collect environmental and gas-response measurements. The collected sensor data is processed and transmitted through Wi-Fi to a cloud-based automation platform using HTTP communication.

The n8n automation platform receives the sensor readings through a webhook and coordinates data processing, cloud storage, AI analysis, and notification services. ThingSpeak is used for sensor visualization and historical analytics, while Google Sheets maintains structured monitoring records. An AI-based analysis component evaluates the incoming measurements and historical patterns to estimate potential food deterioration risk using validated food-specific reference data and machine-learning models.

The system also incorporates an automated notification mechanism using Telegram, Gmail, and AI-generated voice alerts. When abnormal monitoring conditions are detected, users receive immediate notifications containing sensor readings, risk classification, and recommended inspection actions. A web-based dashboard provides a centralized interface for monitoring sensor values, environmental trends, and system status.

The proposed FreshGuard AI architecture demonstrates how IoT sensors, cloud analytics, AI-based decision support, and workflow automation can be integrated into a smart food-monitoring solution. The system is intended as a prototype for food-storage condition monitoring and requires experimental validation before its predictions can be used for food-safety decisions.

Keywords: ESP32, Internet of Things, Food Spoilage Detection, Artificial Intelligence, MQ-4, DHT11, n8n Automation, Telegram Notifications, Voice Alerts, Google Sheets, ThingSpeak, Smart Food Monitoring.

28. Final project outcome

IoT Based Food Spoilage Detection System using ESP32 | DHT11 | MQ4 | Moi... | Iot, Arduino, Detection
Kotak Makan Ciptaan Siswa SMAN 2 Cilacap Ini Bisa Deteksi Makanan Basi
Cold Chain Auditor: Real-Time Trust Score & Web Dashboard - Hackster.io

The completed FreshGuard AI project will demonstrate the integration of:

Technology

Final functionality

ESP32

Sensor monitoring and Wi-Fi connectivity

MQ-4

Methane-sensitive gas response

DHT11

Temperature and humidity monitoring

Moisture sensor

Moisture-related measurements

AI/ML

Food-specific deterioration risk estimation

n8n

Automated workflow orchestration

AI Agent

Sensor-data interpretation and recommendations

Telegram

Instant text notifications

Telegram Voice

Automated audio notifications

Gmail

Email alerts and reports

Google Sheets

Historical data storage

ThingSpeak

Cloud charts and analytics

Web dashboard

Centralized monitoring interface

Final conclusion: FreshGuard AI provides a practical framework for combining embedded systems, IoT, machine learning, cloud analytics, and agentic workflow automation. Its key innovation is the integration of multi-sensor monitoring with automated AI-assisted analysis and multi-channel notifications in a single system.

29. Recommended development order

I recommend building the project in three versions rather than attempting every feature simultaneously.

Version 1 – Basic prototype

ESP32 + Sensors + ThingSpeak

  • Complete hardware wiring.

  • ESP32 Arduino firmware.

  • Sensor readings.

  • ThingSpeak charts.

Version 2 – IoT automation

n8n + Telegram + Gmail + Google Sheets

  • Webhook communication.

  • Cloud logging.

  • Automated notifications.

  • Telegram voice alerts.

Version 3 – Advanced AI system

AI Agent + Machine Learning + Web Dashboard

  • Food-specific ML model.

  • AI Agent analysis.

  • Risk prediction.

  • Real-time dashboard.

  • Historical trend analysis.

My recommendation: First make the ESP32-to-n8n-to-Telegram pipeline work. Once that is reliable, add Google Sheets, ThingSpeak, voice alerts, and finally the food-specific AI model. This makes the project easier to demonstrate, debug, and document.

You can also sign in if you want to keep the project documentation and future development discussions together in your ChatGPT history.

 

FreshGuard AI — Full Project Documentation

FreshGuard AI is an IoT-based food-spoilage detection system that uses an ESP32, gas/temperature/humidity/moisture sensors, a cloud dashboard, and an n8n automation workflow to classify freshness risk and send Telegram, Gmail, and AI voice alerts. The ESP32 publishes readings to ThingSpeak using its REST API, while n8n evaluates thresholds/rules, logs events to Google Sheets, and triggers notifications.[mathworks][mathworks][docs.n8n]

1. Project Overview

The system continuously monitors storage conditions around food items—such as fruits, vegetables, dairy, cooked food, or a small smart container/refrigerator compartment. It detects abnormal volatile gas levels, temperature, humidity, and moisture, then computes a Freshness Index and Spoilage Risk Level.

Parameter Sensor What it indicates
Methane / combustible gas MQ-4 Gas released during decay, fermentation, and spoilage
Temperature DHT11 Warm conditions accelerate microbial growth
Humidity DHT11 High humidity promotes mold and bacterial activity
Moisture / leakage Capacitive soil-moisture sensor Excess moisture, spillage, or wet storage conditions
Connectivity / device status ESP32 Wi-Fi Online/offline and fault detection

ThingSpeak supports writing sensor data through HTTP GET/POST using a channel Write API Key, making it suitable for ESP32 telemetry and real-time charts.[mathworks][mathworks][mathworks]

2. System Architecture

                 ┌──────────────────────────────┐
                 │        FOOD STORAGE BOX       │
                 └───────────────┬──────────────┘
                                 │
        ┌────────────────────────┼────────────────────────┐
        │                        │                        │
   ┌────▼─────┐            ┌─────▼─────┐            ┌─────▼─────┐
   │  MQ-4    │            │   DHT11   │            │ Moisture  │
   │ Gas      │            │ Temp/Hum  │            │ Sensor    │
   └────┬─────┘            └─────┬─────┘            └─────┬─────┘
        │ Analog                 │ Digital                │ Analog
        └───────────────┬────────┴────────────────────────┘
                        │
                 ┌──────▼──────┐
                 │    ESP32     │
                 │ Wi-Fi + Logic│
                 └──────┬──────┘
                        │ HTTP POST / GET
                 ┌──────▼──────┐
                 │  ThingSpeak  │
                 │ Cloud Channel│
                 └──────┬──────┘
                        │ Read API / Webhook
                 ┌──────▼──────┐
                 │     n8n      │
                 │ AI Workflow  │
                 └──┬───┬───┬──┘
                    │   │   │
        ┌───────────┘   │   └───────────┐
        │               │               │
┌───────▼──────┐ ┌──────▼──────┐ ┌──────▼────────┐
│ Google Sheets│ │   Gmail     │ │   Telegram    │
│ Event log    │ │ Email alert │ │ Text + Voice  │
└──────────────┘ └─────────────┘ └───────────────┘

3. Working Principle

  1. The ESP32 reads MQ-4 gas, DHT11 temperature/humidity, and moisture values every 15–30 seconds.
  2. It converts raw analog values into calibrated engineering values.
  3. It calculates a weighted Freshness Index from all parameters.
  4. The ESP32 sends the data to ThingSpeak’s /update endpoint using its Write API Key.[mathworks][docs.espressif]
  5. n8n periodically reads the latest ThingSpeak data or receives it through a webhook.
  6. n8n applies rule-based logic and optional AI analysis to classify the condition.
  7. If spoilage risk is detected, n8n sends a Telegram message, optional Telegram voice alert, Gmail email, and writes an event row to Google Sheets. n8n’s Telegram node supports message operations and audio sending through Telegram’s Bot API.[docs.n8n][docs.n8n][github]

4. Freshness Logic

Use a simple weighted scoring model first; it is reliable, explainable, and easy to demonstrate.

Freshness Index = 100 - Gas Risk - Temperature Risk - Humidity Risk - Moisture Risk
Condition Risk contribution
MQ-4 value above threshold 40 points
Temperature above 30°C 20 points
Humidity above 80% 20 points
Moisture above wet threshold 20 points
Freshness Index Status Alert
80–100 Fresh No alert
60–79 Monitor Telegram warning
40–59 Spoilage likely Telegram + Gmail
0–39 High spoilage risk Telegram text + voice + Gmail + Sheet log

Example: gas risk 40, temperature risk 20, humidity risk 0, moisture risk 0 gives a Freshness Index of 40, so the system reports “Spoilage likely.”

5. Hardware Required

Component Quantity Purpose
ESP32 development board 1 Main controller and Wi-Fi module
MQ-4 gas sensor module 1 Detects methane/combustible spoilage gases
DHT11 temperature/humidity sensor 1 Measures storage temperature and humidity
Capacitive soil-moisture sensor 1 Detects excess moisture or leakage
16×2 I2C LCD, optional 1 Local display
Buzzer / LED, optional 1 Local warning
5V power adapter or power bank 1 Power supply
Breadboard, jumper wires, enclosure 1 set Prototyping and food-safe mounting

Important: MQ-4 sensors require a warm-up period, typically several minutes, before readings stabilize. Do not place electronics directly in contact with wet food; use a sealed sensor compartment or external probe.

6. Circuit / Schematic Connections

ESP32 Pin        Sensor / Module Pin
---------        -------------------
3V3         ───  DHT11 VCC
GND         ───  DHT11 GND
GPIO 4      ───  DHT11 DATA

3V3         ───  MQ-4 VCC
GND         ───  MQ-4 GND
GPIO 34     ───  MQ-4 A0

3V3         ───  Moisture Sensor VCC
GND         ───  Moisture Sensor GND
GPIO 35     ───  Moisture Sensor AOUT

GPIO 2      ───  Buzzer +
GND         ───  Buzzer -

GPIO 25     ───  Red LED +
GND         ───  Red LED - through 220Ω resistor

ASCII Schematic

                         ┌──────────────────┐
                         │      ESP32       │
                         │                  │
        MQ-4 A0 ─────────┤ GPIO34           │
   Moisture AOUT ────────┤ GPIO35           │
        DHT11 DATA ──────┤ GPIO4            │
        Buzzer + ────────┤ GPIO2            │
        Red LED + ───────┤ GPIO25           │
                         │                  │
        MQ-4 VCC ────────┤ 3V3              │
   Moisture VCC ─────────┤ 3V3              │
        DHT11 VCC ───────┤ 3V3              │
                         │                  │
        All GND ─────────┤ GND              │
                         └──────────────────┘

ESP32 ADC pins such as GPIO34 and GPIO35 are input-only and suitable for analog sensor outputs. The capacitive moisture sensor’s analog output varies with moisture level.[esp32io]

7. ThingSpeak Setup

  1. Create a free ThingSpeak account.
  2. Create a new channel named FreshGuard AI.
  3. Enable and name the fields:

    • Field 1: gas
    • Field 2: temperature
    • Field 3: humidity
    • Field 4: moisture
    • Field 5: freshness
    • Field 6: risk_level
  4. Open API Keys and copy the Write API Key.
  5. Use MATLAB Analysis, MATLAB Visualization, or n8n to create alerts.

ThingSpeak’s REST API supports updating channel data through HTTP GET or POST, and the Write API Key is required to publish data to a channel.[mathworks][mathworks][mathworks]

8. ESP32 Firmware Code

Install these Arduino libraries:

  • WiFi.h — built into ESP32 Arduino core
  • HTTPClient.h — built into ESP32 Arduino core
  • DHT sensor library by Adafruit
  • Adafruit Unified Sensor
/*
  FreshGuard AI - Food Spoilage Detection System
  ESP32 + MQ-4 + DHT11 + Moisture Sensor + ThingSpeak
*/

#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"

// ---------- Wi-Fi ----------
const char* WIFI_SSID     = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";

// ---------- ThingSpeak ----------
const char* THINGSPEAK_HOST = "api.thingspeak.com";
String WRITE_API_KEY = "YOUR_THINGSPEAK_WRITE_API_KEY";

// ---------- Pins ----------
#define DHTPIN 4
#define DHTTYPE DHT11
#define MQ4_PIN 34
#define MOISTURE_PIN 35
#define BUZZER_PIN 2
#define LED_PIN 25

DHT dht(DHTPIN, DHTTYPE);

// ---------- Calibration ----------
int AIR_GAS_VALUE = 800;       // Calibrate in clean air
int WET_MOISTURE_VALUE = 2200; // Calibrate for wet condition

// ---------- Thresholds ----------
float TEMP_LIMIT = 30.0;
float HUM_LIMIT = 80.0;

unsigned long lastUpload = 0;
const unsigned long UPLOAD_INTERVAL = 20000; // 20 seconds

void setup() {
  Serial.begin(115200);
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);

  dht.begin();

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.print("Connected. IP: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  if (millis() - lastUpload >= UPLOAD_INTERVAL) {
    lastUpload = millis();

    float temperature = dht.readTemperature();
    float humidity = dht.readHumidity();
    int gasRaw = analogRead(MQ4_PIN);
    int moistureRaw = analogRead(MOISTURE_PIN);

    if (isnan(temperature) || isnan(humidity)) {
      Serial.println("DHT11 read failed");
      sendFaultAlert("DHT11 sensor failure");
      return;
    }

    int gasRisk = calculateGasRisk(gasRaw);
    int tempRisk = temperature > TEMP_LIMIT ? 20 : 0;
    int humRisk = humidity > HUM_LIMIT ? 20 : 0;
    int moistureRisk = moistureRaw < WET_MOISTURE_VALUE ? 20 : 0;

    int freshness = 100 - gasRisk - tempRisk - humRisk - moistureRisk;
    if (freshness < 0) freshness = 0;

    String riskLevel;
    if (freshness >= 80) riskLevel = "FRESH";
    else if (freshness >= 60) riskLevel = "MONITOR";
    else if (freshness >= 40) riskLevel = "SPOILAGE_LIKELY";
    else riskLevel = "HIGH_RISK";

    Serial.printf("Gas:%d Temp:%.1fC Hum:%.1f%% Moisture:%d Freshness:%d Status:%s\n",
                  gasRaw, temperature, humidity, moistureRaw, freshness, riskLevel.c_str());

    if (freshness < 60) {
      digitalWrite(BUZZER_PIN, HIGH);
      digitalWrite(LED_PIN, HIGH);
    } else {
      digitalWrite(BUZZER_PIN, LOW);
      digitalWrite(LED_PIN, LOW);
    }

    uploadToThingSpeak(gasRaw, temperature, humidity, moistureRaw, freshness, riskLevel);
  }
}

int calculateGasRisk(int gasRaw) {
  if (gasRaw > AIR_GAS_VALUE + 900) return 40;
  if (gasRaw > AIR_GAS_VALUE + 500) return 25;
  if (gasRaw > AIR_GAS_VALUE + 200) return 10;
  return 0;
}

void uploadToThingSpeak(int gas, float temp, float hum, int moisture, int freshness, String risk) {
  if (WiFi.status() != WL_CONNECTED) {
    WiFi.reconnect();
    return;
  }

  HTTPClient http;
  String url = "http://" + String(THINGSPEAK_HOST) + "/update?api_key=" + WRITE_API_KEY +
               "&field1=" + String(gas) +
               "&field2=" + String(temp, 1) +
               "&field3=" + String(hum, 1) +
               "&field4=" + String(moisture) +
               "&field5=" + String(freshness) +
               "&field6=" + risk;

  http.begin(url);
  int httpCode = http.GET();

  if (httpCode > 0) {
    Serial.println("ThingSpeak response: " + String(httpCode));
  } else {
    Serial.println("ThingSpeak upload failed");
    sendFaultAlert("ThingSpeak upload failed");
  }

  http.end();
}

void sendFaultAlert(String issue) {
  Serial.println("FAULT: " + issue);
  // Optional: send fault to n8n webhook
  HTTPClient http;
  http.begin("https://YOUR_N8N_SERVER/webhook/freshguard-fault");
  http.addHeader("Content-Type", "application/json");

  String payload = "{\"device\":\"ESP32-01\",\"issue\":\"" + issue + "\",\"time\":\"" + String(millis()) + "\"}";
  int code = http.POST(payload);
  Serial.println("Fault webhook response: " + String(code));
  http.end();
}

9. n8n Automation Workflow

Workflow Flow

Schedule Trigger
       │
       ▼
ThingSpeak: Read Latest Entry
       │
       ▼
IF Node: Freshness < 80?
       │
       ├── No ──► Stop
       │
       ▼
Switch Node: Risk Level
       │
       ├── MONITOR ────────────► Telegram Warning
       ├── SPOILAGE_LIKELY ────► Telegram + Gmail + Google Sheets
       └── HIGH_RISK ──────────► Telegram + Voice + Gmail + Google Sheets

Required n8n Nodes

  1. Schedule Trigger — run every 1 or 5 minutes.
  2. HTTP Request — call ThingSpeak Read API.
  3. Set / Edit Fields — extract gas, temperature, humidity, moisture, freshness, and risk level.
  4. IF — check whether freshness < 80.
  5. Switch — route by risk_level.
  6. Telegram — send text alerts.
  7. Telegram: Send Audio — send AI-generated voice alert.
  8. Gmail — send email alerts.
  9. Google Sheets — append event history.
  10. OpenAI / HTTP Request — optional AI-generated alert message and voice script.

n8n’s Telegram integration includes a Send Audio operation, which uses Telegram’s sendAudio Bot API method.[docs.n8n][docs.n8n]

Example Telegram Message

🚨 FreshGuard AI Alert

Food Storage Unit: Kitchen Container 1
Freshness Index: 38/100
Risk Level: HIGH RISK

Gas Level: 2450
Temperature: 33.4°C
Humidity: 86%
Moisture: Wet condition detected

Recommended Action:
Check the food immediately. Move it to a cooler, dry location and inspect for odor, mold, leakage, or spoilage.

10. AI Agent Logic

The AI agent does not replace sensor thresholds; it improves the alert by interpreting multiple conditions together.

AI Prompt

You are FreshGuard AI, a food safety assistant.

Given the following sensor data, analyze the spoilage risk:
- Gas value: {{gas}}
- Temperature: {{temperature}} °C
- Humidity: {{humidity}} %
- Moisture: {{moisture}}
- Freshness Index: {{freshness}}
- Rule-based status: {{risk_level}}

Return:
1. A short spoilage-risk explanation.
2. The most likely cause.
3. One clear recommended action.
4. A short voice-alert script under 30 words.

Do not claim the food is definitely unsafe. Recommend inspection when uncertain.

Example AI Output

Risk: High spoilage likelihood.

Elevated gas, high temperature, high humidity, and moisture suggest accelerated microbial activity or leakage.

Recommended action: Inspect the food now, remove any spoiled items, clean the container, and store food in a cooler, dry place.

Voice alert: “Warning. Food spoilage risk detected. Please inspect the container immediately.”

11. Google Sheets Structure

Create a Google Sheet named FreshGuard_AI_Logs with these columns:

Timestamp Device ID Gas Temperature Humidity Moisture Freshness Risk Level AI Summary Alert Sent
2026-11-01 22:45 ESP32-01 2450 33.4 86 Wet 38 HIGH_RISK High spoilage likelihood Telegram, Gmail, Voice

12. Web Dashboard

ThingSpeak can act as the primary cloud dashboard because it plots each field over time and supports public/private channel views.[mathworks][mathworks]

Dashboard Widgets

  • Gas level line chart
  • Temperature line chart
  • Humidity line chart
  • Moisture status chart
  • Freshness Index gauge
  • Risk-level indicator
  • Latest reading table
  • Alert history table from Google Sheets

Optional Custom Web Dashboard

For a custom dashboard, create a simple HTML page that calls the ThingSpeak Read API every 15 seconds and displays values using Chart.js. The ESP32 only needs to publish data; the browser or n8n can read the channel for visualization.

13. Testing Procedure

  1. Power test: Connect ESP32 via USB and confirm the board boots.
  2. Wi-Fi test: Verify the serial monitor shows a successful connection.
  3. DHT11 test: Breathe near the sensor; humidity should rise.
  4. MQ-4 test: After warm-up, expose it carefully to a small safe gas source or use a controlled test gas per safety guidance; do not use open flames or hazardous gas.
  5. Moisture test: Touch the sensor probe to a damp cloth; the reading should change.
  6. ThingSpeak test: Confirm new points appear in each field.
  7. n8n test: Force a low Freshness Index and verify Telegram, Gmail, and Google Sheets responses.
  8. Voice test: Confirm the Telegram audio file plays correctly.
  9. Fault test: Disconnect DHT11 temporarily and confirm the fault webhook/alert works.

14. Safety and Accuracy Notes

  • MQ-4 detects combustible gases, especially methane, but it is not a certified food-safety or gas-leak safety device.
  • Use sensor readings as an early-warning indicator, not as proof that food is safe to eat.
  • Calibrate each sensor in the actual storage environment.
  • Keep the MQ-4 away from direct moisture and condensation.
  • Use food-safe separation between electronics and food.
  • For a commercial or health-critical deployment, add proper enclosure design, sensor calibration, power backup, and compliance testing.

15. Future Enhancements

  • Add MQ-135 for broader air-quality and ammonia/VOC detection.
  • Add ESP32-CAM for mold or food-image classification.
  • Add GPS or QR-code tagging for inventory tracking.
  • Use TensorFlow Lite Micro for on-device anomaly detection.
  • Add a mobile app dashboard using Blynk, Flutter, or a PWA.
  • Add predictive spoilage forecasting using historical ThingSpeak data.
  • Add automatic fan, dehumidifier, or refrigerator control through a relay.

This design gives you a complete AI-enabled, multi-sensor, cloud-connected food spoilage detection system with ESP32 hardware, real-time ThingSpeak analytics, automated n8n workflows, Google Sheets logging, Gmail alerts, and Telegram text plus voice notifications.[mathworks][mathworks][docs.n8n][docs.n8n]

No comments:

Post a Comment