Skip to main content

An Intelligent IoT and Machine Learning Framework for Real-Time Food Spoilage Detection and Quality

Page 1


International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 p-ISSN: 2395-0072

Volume: 13 Issue: 06 | Jun 2026 www.irjet.net

An Intelligent IoT and Machine Learning Framework for Real-Time Food Spoilage Detection and Quality Monitoring

1Post Graduate Student, Dept of Masters of Computer Application, Vivekanand Education Society's Institute Of Technology Chembur, Mumbai

2Post Graduate Student, Dept of Masters of Computer Application, Vivekanand Education Society's Institute Of Technology Chembur, Mumbai

3Professor, Dept of Masters of Computer Application, Vivekanand Education Society's Institute Of Technology Chembur, Mumbai

Abstract-Food spoilage is a problem that causes a lot of financial losses and health risks all over the world. Most food monitoring systems that use the internet of things rely on rules that do not work well for different types of food and changing environments. This study suggests a way to monitor food quality that uses a device with many sensors and a machine learning system to predict when food will spoil in real time. The system uses a computer called an ESP32 that is connected to many sensors like MQ3, MQ4 and MQ135 gas sensors, a DHT22 temperature and humidity sensor, an LDR light sensor and a pH sensor. The sensor data is sent over Wi-Fi to a platform called AWS IoT Core, where a special machine learning model is used to classify how fresh the food is and predict how the quality will change over time.The system is very good at classifying food freshness with an accuracy of 94.3% for food like dairy, fruits and packaged goods. It can send alerts in under 2 seconds. This system is better, than systems that just use simple rules because it can adapt to different situations it has fewer false alerts and it can predict how long the food will last, which helps manage the supply chain and reduce food waste.

Key Words: IoT, food quality monitoring, machine learning, Random Forest, LSTM, ESP32, food spoilage detection, smart supply chain, AWS IoT Core.

1.INTRODUCTION

Therearesignificantissueswiththefoodsafetyandquality monitoring processes throughout the modern global food supplychain.TheFoodandAgricultureOrganizationofthe United Nations reports that around one-third of food produced for human consumption is lost or wasted each year, much of it due to insufficient monitoring of the environmental conditions during storage and/or transportation[1].Environmentalvariablefluctuations(e.g., temperature,humidity,ethanolconcentrationintheair,and exposure to light) can significantly increase the rate of spoilageduetomicrobialactivity,oxidation,andenzymatic reactions;allofthesearemeasuredbyphysicalparameters. Most warehouse and distribution facilities use manual inspections on a periodic basis to monitor food, which is

labour-intensive and prone to human error. While some sensor-basedIoTsystemshavebeendeveloped(toautomate environmentalmonitoring),mostofthesedeployedsystems apply static rules (threshold) to initiate alert events. As a result,binary(yes/norule-based)methodsfailtoaddress the dynamic and nonlinear degradation processes of food and do not adapt to the inherent variability among food types.

This paper presents an intelligent solution for monitoring food quality over time. Machine learning (ML) is an innovative way to significantly change food industry processes as we currently know them through the use of sensor devices and ML algorithms trained on historical datasetsofsensoroutputslabeledwithspoilagefactors.The abilitytoaffordablydeveloppredictivemodelsusingvarious typesofdata,suchashistoricaldatafromdifferentlocations combined in one dataset, allows for much more accurate prediction of food quality deterioration than the previous methodofusingfixedthresholdsalone.

Inparticular,theuseofrecurrentneuralnetworks(RNNs)or LongShort-TermMemory(LSTM)networksisbeneficialfor trainingmodelstopredictfoodqualityovertimebecauseof theirinherentabilitytomodeltime-seriesdatasuchasthat fromsensors.Additionally,thesetypesofRNNswillenable predictiveshelflifedeterminationandallowthefoodindustry tomovefrombeingreactivetoproactivethroughreal-time alertingcapabilitiesthatresultfromcollectedsensorandML data.

This research presents an "end-to-end" intelligent frameworkthatconsistsof:

•Aheterogeneoussensordevice(ESP32)withmultipletypes of sensors collecting and transmitting data relating to gas composition,temperature,humidity,lightintensity,andpH levelinreal-timetoacloudbasedplatformforbuildingand maintainingMLpredictivemodels.

• A hybrid ML pipeline that uses both a Random Forest classifiertoclassifythecurrentfreshnessandqualityoffood andanLSTMmodelthatusestemporalinformationtopredict

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 p-ISSN: 2395-0072

Volume: 13 Issue: 06 | Jun 2026 www.irjet.net

spoilagetrendoffoodproducts.

• Integration with AWS IoT Core to provide data storage capabilities, and Firebase to enable real-time alerting by means of mobile push notifications, and a web-based dashboardforeaseofremotemonitoring.

• Validationofthepredictiveclassificationaccuracyofthe models developed on the hybrid ML pipeline using three differentfoodcategorieswithanaccuracyrateof94.3%and anaverageresponsetimeoflessthan2seconds.

2.LITERATURE SURVEY

Numerous studies exist in the area of IoT based food monitoring; however, there is limited use of predictive machinelearningintheexistingdeployments.

Chanthini, et al., created a wireless sensor network based perishablefoodquality-monitoringsystemusingRaspberry Pi as the primary processing device. The moisture, gas, temperature,andhumiditysensorswereintegratedintothe system, and data was displayed via the Xively IoT Cloud platform.Althoughsensorintegrationwassuccessful,thelack of machine learning capability prevented prediction from occurringasallparameterswerebasedonfixedthresholds [1].

Venkatesh, et al.developed a Bluetoothlow energy-based food monitoring system using an nRF52832 Cortex-M4F microprocessor, and VOC and DHT11 sensors were programmedtosenddatatotheThingSpeakcloud.Although the use of Bluetooth low energy reduces battery usage, a singlegassensorlowerstheabilitytoidentifyeverythingthat couldaffectthefoodproductinquestion;therefore,thereis nomachinelearningcomponentinthedevelopmentofthis product[2].

DivyaBharathi,etal.createdafoodmonitoringsystemusing an Arduino Mega 328 microcontroller with the goal of detecting the bacterial contamination of food products throughtemperature,odour,andphsensing;inadditionto usinganofftheshelfbiosensor.Datawasdisplayedonan LCD, however, there was no cloud connectivity or remote monitoringcapabilities, whichwouldhinder itsabilityfor largescalepracticaluse[3].

PrasaathproposedanArduinoUNOfoodspoilagemonitoring projectusingDHT-11,MQ3,andLDRsensorsdisplayedon Freeboard.io.Thissystemprovidesagreatplacetostart,but thenumberofsensorsusedprovidesinsufficientinformation toallowfordetectionofmultiplefoodtypeswhichmayspoil [4].

Kaushaletal.extendedtheprojectbydevelopingasystem basedonanATmegamicrocontrollerusingacomprehensive array of sensors including Temp, LDR, gas, humidity, moisture,IRandaGSMmoduleforcommunicationwiththe

supply chain. When sensor parameters were out of the acceptable/threshold range, a buzzer would be activated. Thisworkestablishedtheimportanceofintegratingthefood supply chain; however, ML was not used for adaptive prediction[5].

Borawakeetal.tooktheprojectonestepfurtherbyusing ArduinoUnowithgasandpHsensorsconnectedtoasimple machine learning model that determines fresh food and spoiled food. These models are not capable of temporal reasoning, and do not have multiple classes available by whichtodifferentiatevariousfoodtypes[11].

Nguyenetal.recentlydevelopedabatteryfree,NFCbased foodmonitoringunitwithpHandCO2measuringcapabilities as the first step toward implementing a more advanced hardwaresolution.However,thissystemwasbuiltwith such a limited energy model that it placed significant restrictionsontheprocessingpowerofthesystem,making ondeviceintegrationofmachinelearningnearlyimpossible atthistime[7].

ThecomparativeanalysisinTableIillustratesthepositioning oftheproposedsystemrelativetopriorart,highlightingthe gap this work addresses namely, the absence of adaptive, multi-class,temporally-awareML-drivenmonitoring.

TableIshowshowthenewsystemispositionedcompared with previous work and identifies a gap in technology that thisresearchworkstofill:Thereisnoadaptive,multi-class, temporally-awareMLmonitoredsystem.

Table-1: ComparativeAnalysisofExistingFoodMonitoring Systems

3. PROPOSED SYSTEM ARCHITECTURE

The proposed system is organised into three functional layers: the sensor acquisition layer, the cloud processing layer,andtheuserinterfacelayer.

A. The Layer That Acquires Sensors The ESP32 microcontrollercanbeconsideredtheprimarycomponentof asensornode;ithasadual-coreXtensaLX6processorand has built-in Wi-Fi, Bluetooth, and 34 programmable GPIO pins.ThefollowingsensorsarebeinginterfacedtotheESP32:

Volume: 13 Issue: 06 | Jun 2026 www.irjet.net

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 p-ISSN: 2395-0072

•MQ-3(ethanol/alcoholsensor)–Measuresthepresenceof VOCs (volatile organic compounds) produced by fermentationandspoiling, especiallywith dairyandfruit.

•MQ-4 (methane sensor) – Measures the amount of methanegasgeneratedduringanaerobicdecompositionof food, which is important for food that has been packaged andforprotein-richfood.

•LDR(lightdependentresistor)–Measurestheintensity of light exposure, as it can enhance the lipid oxidation andphoto-degradation ofcertainfoods

•pH sensor (SEN0161) - Measures pH of a food product's liquid, where applicable, such as in beverages andotherliquidfoodproducts

•MQ-135 (air quality/ammonia sensor) – Provides information on ammonia, benzene and sulfide concentrations as they relate to advanced protein decay.

Sensor reading will be taken every 10 seconds and locallybufferedontheSPIFFSfilesystemoftheESP32to ensure continuous data output should there be an intermittentloss of network connectivity. All ofthedata packets will be serializedusing JSON format, andsentvia the MQTT protocol to AWS IoT Core over a TLSencrypted channel.

B. Cloud-Processing and ML-Inference.

Incoming sensor data streams are sent to AWS IoT Core then routed to two parallel processing pipelines via IoT Rules in AWS IoT Core after the data has been received by AWS IoT Core. The first pipeline writes the raw sensor readings toa FirebaseRealtimeDatabaseenabling visualisationsoftherawsensorreadingsonanup-to-date dashboard. The second pipeline triggers (calls) an AWS Lambda function which calls a hosted Model as-a-Service (MaaS)inAmazonSageMaker(AhostedMachineLearning Inference endpoint). The two separate, collaborating machine learning models in the machine learning pipeline: (1). random forest classifier; and RH) measurements (using a 0.5 Hz sampling rate).

(2). multi-class classifier. Random Forest classifier: measures the freshness of the food items classified into three categories (dairy products, fruit, and pantry) and classifies them as Fresh, Borderline, or Spoiled. The featuresuponwhichtherandom forest classifier was trained included:

1. Rolling average of the temperature and humidity duringthe pastfiveminutes (meanandspot);2.Rolling Standard Deviation of the temperature and humidity during the past five minutes (mean and spot); 3.Ratio of Carbon Dioxide (gas ratio) divided by the weight of the food item; and 4. Interaction terms between the temperature and humidity. The performance of the

• DHT22 (temperature and humidity) – Provides accurate ambient temperature (±0.5°C) and relative humidity (±2%

random forest classifier on the out-of-bag (oob) test set was94.3%accurate.

AnLSTMbasedregressionmodeliscreatedtotakeinputs as windows of 30 continuous sensor readings (5 minutes) to generate an estimated time until spoilage (hours).Thearchitectureincludes2stackedLSTMlayers (128 and 64 units) and a linear activation dense output layer. The training of the model was done using Adam OptimizerwithaMeanAbsoluteError(MAE)lossfunction over 80 epochs, and early stopping was applied. The model achieved an MAE of 1.7 hours on the validation dataset,whichwassignificantlybetter than the ARIMA baseline (MAE: 4.2 hours).

C. User Interface Layer

The user interface includes both a Firebase-hosted progressive web app (PWA) and a companion Android app. Both interfaces provide real-time sensor readings, current freshness rating with confidence score, estimated time remaining until spoilage, and historical trendgraphs.Pushnotificationswillbeautomaticallysent using Firebase Cloud Messaging when the classifier indicatesthattheitemisclassifiedasSpoiledorwhenthe LSTMmodelindicatesthattheestimatedtimeremaining until spoilage is less than 6 hours. SMS fallback alerts will be sent via Twilio API for locations where Internet accessisintermittent.

4.DATASET COLLECTION AND MODEL TRAINING

A primary dataset was created from a laboratory controlledstudythatlasted8weeks,collected3different types of foods in 50 samples (fresh milk, bananas and mangoes, packaged goods); and monitored spoilage at varioustemperatures(10degreesCelsius(C),25degrees C, and 35 degrees C). The study employed 10 second intervals to record sensor data (10 seconds) with trained food technologist (using organolpetic assessment and microbiological plate count) evaluating the physical spoilage condition of the samples at hourly intervals.

A total of 12,400 labelled instances making up the classification dataset and 8,900 sequences that were included in the training of the long short term memory (LSTM) model were created from the primary dataset; following the removal of noise in the data due to large deviationsofsensorreadingsfromnormalusingazscore method.Datawassplitintothreeequalcategories(80%

Volume: 13 Issue: 06 | Jun 2026 www.irjet.net

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 p-ISSN: 2395-0072

training, 10% validation, 10% testing) for classification and training. The three mucons (fear, caffeine, and ethanol) from the feature importance (random forests) analysisweremostpredictiveforthesampletypes,such that they made up (combined) 61.2% of the cumulative variance (predictability) of spoilage by aerobic organisms.

5. RESULTS AND DISCUSSION

The proposed system was evaluated across the three food categories under realistic storage simulation conditions. Table II summarises the classification performance of the Random Forest model per food category.

Table II: ClassificationPerformancebyFoodCategory

The overall classification accuracy of 94.3% is a significant improvement over the basic ML integration described in Borawake et al. [11], which achieved approximately 87% classification accuracy for binary (fresh/spoiled) classification tasks. The multi-class formulation of the proposed model, through the intermediate Borderline state,provides additional actionableintelligencetothesupply-chaincommunityby allowing for proactive intervention prior to the onset of totalspoilage.

The mean absolute error for the LSTM time-series predictor for forecasting shelf-life was 1.7 hours. With this level of accuracy, distribution centres are able to make better decisions related to stock rotation, prioritised delivery, and the adjustment of refrigeration settings. The false-positive alert rate during the test period was 3.1%, minimizing the occurrence of unnecessary discarding of food, which is one of the main concernsinthepracticaldeploymentofthetechnology.

The average system latency between sensor reading to pushnotification delivery was1.84 seconds(SD: 0.31 s) under normal network conditions, meeting the requirements for real-time monitoring within warehouse settings. The average power consumption of the ESP32 node during active transmission was 180 mW, which is consistent with continuous mains-powered operation in astoragefacilitysetting.

Unlike purely threshold-based systems like those from

Christiena et al. ([6] ) and Hai Prasaath ([4] ), our suggested system does not require manual threshold calibration for the many different categories of food. Instead,theRandomForestmodelisabletoautomatically adjustthethresholdsithaslearnedforeachfoodcategory asitlearnstheconditionsthatdefinespoilageinthefood category. This greatly decreases the burden of establishing a new system compared to a thresholdbasedsystem.

6. CONCLUSION

In this study, we demonstrated a smart IoT model with the ML model that allows for real-time food spoilage assessment and estimating food quality. The model production combines multiple sensors within an ESP32 networkusinganMLpipelinehostedinthecloud,which is composed of both a Random Forest Classifier and an LSTM model for time sequence predictions that would allow us to both retrieve real-time classification measuresoffoodfreshnessandpredictitsshelflife.The overallmodelwasevaluatedandvalidatedonnumerous multipled food categories, including dairy, fruits, and packaged foods, via performance metrics of 94.3% correctness of the classification measure, a 3.1% false positivemeasure,and1.7hourmeanshelflifeprediction error (all superior performance to existing reported literature results on rule based systems using single modellingapproaches).

Withthisframework,theabilitytoproducetherequired results using an IoT and ML multi-layered approach is made possible by the cloud infrastructure utilizing the AWS IoT Core, SageMaker, and Firebase, which can enable the scalability of architectural deployment into large-scalewarehouseenvironments,withoutconstraint of on-device compute. Future research will address the exploration of federated learning to enable food model personalisation across globally distributed sensor nodes, without the need to centralise raw food data, as well as explore the use of computer vision technology to detect surface spoilage in conjunction with gas and chemicalsensordata.

REFERENCES

[1] B. Chanthini, D. Manivannan, and A. Umamakeswari, "Perishable food quality monitoring: an internet of things (IoT) approach," Int. J.Pure Appl.Math., vol.115, pp.63–66,2017.

[2]A.Venkatesh,T.Saravanakumar,S.Vairamsrinivasan, A. Vigneshwar, and M. Santhosh Kumar, "A food monitoring system based on bluetooth low energy and InternetofThings,"Int.J.Eng.Res.Appl.,vol.7,no.3,pp. 30–34,2017.

[3]K. Divya Bharathi and M. Rajalakshmi, "IoT based

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056 p-ISSN: 2395-0072

food quality detection with bio sensor technology," 2018.

[4]K. Hai Prasaath, "Arduino based smart IoT food qualitymonitoringsystem,"unpublished.

[5] R.K.Kaushal,T.Harini,D.P.Lency,T.Sandhya,andP. Soniya,"IoTbasedsmartfoodmonitoringsystem,"Int.J. CurrentEng.Sci.Res.,vol.6,no.6,pp.73–76,2019.

[6] Christiena, H. S. Dhanushitha, N. Arsheya, and C. N. Ramya, "Survey on food quality monitoring system," IRJET,2020.

[7]T.-B. Nguyen, T.-H. Nguyen, and W.-Y. Chung, "Battery-freeandnoninvasiveestimationoffoodpHand CO2 concentration for food monitoring based on pressuremeasurement,"Sensors,vol.20,no.20,p.5853, 2020.

[8]R. Robin, G. E. Bridges, and S. Bhadra, "Wireless passive sensors for food quality monitoring: improving thesafetyoffoodproducts,"IEEEAntennasPropag.Mag., vol.62,no.5, pp.76–89,2020.

[9]Prajwal Atkare, P. Vaishali, and D. Sumit, "Food qualitydetectionand monitoringsystem," in Proc. 2020 IEEE Int. Students' Conf. Electrical, Electronics and ComputerScience(SCEECS),pp.1–4,2020.

[10]Jayakumar,C.H.Suman,C. H.Abhishek,S.Lakshmi, N. Shivprasad, and K. Rakshitha, "A literature review on techniquestodetectfoodfreshness,"unpublished.

[11]M.P.Borawake,A.Sharma,U.Shaikh,S.Barkade,and R.Paturkar,"E-gadgettodetectfoodfreshnessusingIoT andML,"unpublished.

[12]S. M. Hasan, M. R. Ahsan, and M. D. A. Satter, "IoTcloud-based low-cost temperature, humidity, and dust monitoring system to prevent food poisoning," in Proc. 2021 3rd Int. Conf. Electrical & Electronic Engineering (ICEEE),pp.21–24,2021.

[13] S. Mishra and C. S. P. Naidu, "Food spoilage detectionsystem,"IRJMETS,vol.4,no.4,2022.

[14]L.Breiman, "Randomforests,"Mach.Learn.,vol.45, pp.5–32,2001.

[15]S. Hochreiter and J. Schmidhuber, "Long short-term memory," Neural Comput., vol. 9, no. 8, pp. 1735–17801997.

Volume: 13 Issue: 06 | Jun 2026 www.irjet.net © 2026, IRJET | Impact Factor value: 8.315 | ISO 9001:2008

| Page

Turn static files into dynamic content formats.

Create a flipbook
An Intelligent IoT and Machine Learning Framework for Real-Time Food Spoilage Detection and Quality by IRJET Journal - Issuu