Siddhant Kumar
Project 033 Β· Agriculture

Grain Silo Monitor.

Reads temperature and moisture at several depths inside a stored-grain mass and warns before a hot spot turns into a spoilage pocket.

Intermediate 10–16 hours 37 min read SensorsStorageAlerts
Jump to source Bill of materials
Grain Silo Monitor β€” reference build illustration MCU VCC Β· GND Β· SIG Β· NC
Difficulty
Intermediate
Build time
10–16 hours
Indicative cost
β‚Ή3,200 – β‚Ή4,200
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Agriculture
Last updated
28 July 2026
Contents β€” 26 sections

Project Overview

Reads temperature and moisture at several depths inside a stored-grain mass and warns before a hot spot turns into a spoilage pocket.

Stored grain is a living, respiring ecosystem. Even after harvest the kernels breathe, the moulds and insects living on them breathe, and every gram of that respiration releases heat, water and carbon dioxide. In a sealed silo those products cannot escape, so a small pocket of slightly-too-wet grain warms up, the warmth drives moisture migration toward it, the added moisture accelerates mould growth, and within days a self-reinforcing hot spot forms that can spoil tonnes of grain and, in extreme cases, catch fire. The whole loss is silent β€” from the outside the silo looks exactly the same. This project puts sensors inside the grain so the hot spot is visible on day one instead of week three.

The monitor drops a cable of temperature sensors down the centre of the silo, samples grain-interface humidity, and watches the headspace COβ‚‚ concentration β€” the single most sensitive early indicator of biological activity, because respiration produces measurable COβ‚‚ long before a temperature rise is obvious. An ESP32 logs all of this on a schedule, computes the grain's equilibrium moisture content from temperature and humidity, and sends the profile over LoRa to a shed or phone. When any depth trends upward against its neighbours, or COβ‚‚ climbs, it raises an alarm and tells the operator which layer and roughly how deep to aim the aeration fan or unload from.

The design goal is a device a farmer or a small co-operative can actually deploy: it runs for a whole storage season on a solar-charged battery, survives the dust and the temperature swing of a metal silo, needs no wiring back to mains, and speaks in the language the operator already uses β€” "top third is warming, moisture 15%, ventilate" rather than a wall of raw numbers.

An ESP32 development board with the ESP-WROOM-32 module and USB connector
ESP32 module β€” the low-power controller that samples the depth cable, computes EMC and drives the LoRa link. Photograph sourced from Wikimedia Commons β€” ESP32 Espressif ESP-WROOM-32 Dev Board.jpg. Reused under the licence stated on that page; please check it before republishing.

What this project does

  • Measures grain temperature at several depths on a single sensor cable
  • Tracks headspace humidity and computes grain equilibrium moisture content (EMC)
  • Monitors COβ‚‚ in the silo headspace as the earliest sign of biological activity
  • Detects a developing hot spot by comparing each depth against its neighbours and its own history
  • Sends the depth profile and alerts over long-range LoRa to a base station or phone
  • Logs to local storage so a communication gap never loses the record
  • Runs a full storage season on solar + battery with no mains wiring

Real-World Applications

SettingHow it is used
On-farm storageA farmer holding wheat, maize or paddy for a better price weeks or months after harvest, protecting the crop from silent spoilage.
Co-operative / FPO warehousesVillage-level aggregators storing many members' grain, where one undetected hot spot means many families' losses and disputes.
Seed storageSeed viability collapses with heat and moisture; continuous monitoring protects germination rate, which is the seed's entire value.
Procurement / mandi godownsGovernment or trader stores holding grain to buffer prices, where fumigation and aeration decisions need data, not guesswork.

Deployment contexts where a build of this kind earns its keep.

Features & Capabilities

  • Multi-point temperature cable β€” one hot spot cannot hide behind an average
  • COβ‚‚ early warning: respiration is detectable before temperature moves
  • Equilibrium moisture content derived on-device from temperature + humidity
  • Rate-of-rise and neighbour-difference alarms, not just fixed thresholds
  • Long-range LoRa so the silo need not be near Wi-Fi or mains
  • Season-long unattended operation on a small solar panel
  • Operator-language alerts naming the affected layer and suggested action

Difficulty, Time & Required Skills

AttributeValue
Difficulty levelIntermediate
Estimated completion time10–16 hours
Indicative build costβ‚Ή3,200 – β‚Ή4,200
Primary disciplineAgriculture
Reference platformESP32 DevKit V1 (ESP-WROOM-32)

Skills you should have (or will pick up)

  • Wiring a chain of 1-Wire (DS18B20) sensors on a single bus
  • Reading an NDIR COβ‚‚ sensor over UART
  • Basic grain-storage physics: EMC, respiration, moisture migration
  • LoRa point-to-point links and simple packet framing
  • Solar + lithium power budgeting for seasonal deployment

Bill of Materials

Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift β€” treat them as a budgeting guide, not a quotation.

ComponentKey specificationQtyApprox. cost
ESP32 DevKit V1 (ESP-WROOM-32)
Wi-Fi transmit bursts peak near 500 mA β€” size the regulator accordingly.
Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18Γ— 12-bit ADC, 2Γ— 8-bit DAC1β‚Ή450
DS18B20 waterproof temperature probe
Dozens can share one GPIO β€” you address them by ROM code.
βˆ’55 to +125 Β°C, Β±0.5 Β°C from βˆ’10 to +85 Β°C, 9–12-bit resolution, unique 64-bit ROM ID6β‚Ή960
SHT31-D temperature + humidity sensor
The built-in heater burns off condensation β€” essential for outdoor or greenhouse use.
βˆ’40 to +125 Β°C Β±0.2 Β°C, 0–100 %RH Β±2 %, 1 Hz–10 Hz, on-chip heater1β‚Ή620
MH-Z19B NDIR COβ‚‚ sensor
Disable auto-baseline calibration (ABC) for sealed rooms or it drifts to 400 ppm.
0–5000 ppm Β±(50 ppm + 5 %), NDIR, 60 s warm-up, UART + PWM output1β‚Ή2,600
SX1278 LoRa 433 MHz module (Ra-02)
Never power the radio without an antenna β€” the PA will destroy itself.
βˆ’148 dBm sensitivity, +20 dBm output, up to 10 km line of sight, SF7–SF121β‚Ή480
20 W 12 V polycrystalline solar panel
Rated watts assume 1000 W/mΒ² β€” plan for 60–70 % of nameplate in real installs.
Vmp 17.5 V, Imp 1.14 A, Voc 21.6 V, 350 Γ— 290 mm, aluminium frame1β‚Ή1,200
TP4056 Li-ion charger + DW01 protection
Buy the version *with* protection ICs β€” the bare charger will over-discharge your cell.
1 A programmable CC/CV charge to 4.2 V Β±1 %, over-discharge and short protection1β‚Ή45
18650 Li-ion cell 3400 mAh + holder
Never charge below 0 Β°C; always use a protected cell or a BMS.
3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge1β‚Ή450
Sensor cable + waterproof DS18B20 probes
Or build from individual waterproof probes on shielded cable
Pre-wired 1-Wire chain, stainless probes, food-safe jacket, 3–6 m1β‚Ή900
Weatherproof field enclosure
Electronics stay outside the grain; only probes go in
IP65, UV-stable, cable glands, mounts on silo roof1β‚Ή450
Grain-safe cable gland / eye-boltSeals the probe cable at the roof hatch, takes the hanging weight1β‚Ή120

Estimated total: β‚Ή8,275, excluding tools, shipping and consumables.

Tools and consumables

  • Soldering iron (temperature controlled, 350 Β°C) with 0.8 mm 60/40 or lead-free solder
  • Digital multimeter β€” continuity, DC volts and current ranges
  • Wire strippers, flush cutters and a small set of precision screwdrivers
  • Heat-shrink tubing and a heat gun (or a lighter, carefully)
  • A laptop with a USB port and the toolchain listed above

Hardware Specifications

PartSpecificationSupplyInterfaceReference
ESP32 DevKit V1 (ESP-WROOM-32)Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18Γ— 12-bit ADC, 2Γ— 8-bit DAC3.3 V logic / 5 V USBUART, SPI, IΒ²C, IΒ²S, CAN, PWMDatasheet
DS18B20 waterproof temperature probeβˆ’55 to +125 Β°C, Β±0.5 Β°C from βˆ’10 to +85 Β°C, 9–12-bit resolution, unique 64-bit ROM ID3.0–5.5 V1-Wire (multi-drop)Datasheet
SHT31-D temperature + humidity sensorβˆ’40 to +125 Β°C Β±0.2 Β°C, 0–100 %RH Β±2 %, 1 Hz–10 Hz, on-chip heater2.4–5.5 VIΒ²C (0x44/0x45)Datasheet
MH-Z19B NDIR COβ‚‚ sensor0–5000 ppm Β±(50 ppm + 5 %), NDIR, 60 s warm-up, UART + PWM output4.5–5.5 VUART 9600 8N1, PWMDatasheet
SX1278 LoRa 433 MHz module (Ra-02)βˆ’148 dBm sensitivity, +20 dBm output, up to 10 km line of sight, SF7–SF123.3 VSPIDatasheet
20 W 12 V polycrystalline solar panelVmp 17.5 V, Imp 1.14 A, Voc 21.6 V, 350 Γ— 290 mm, aluminium frame12 V nominalMC4 / screw terminalsDatasheet
TP4056 Li-ion charger + DW01 protection1 A programmable CC/CV charge to 4.2 V Β±1 %, over-discharge and short protection4.5–5.5 V inmicro-USB / padsDatasheet
18650 Li-ion cell 3400 mAh + holder3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge3.0–4.2 VHolder / spot-welded tabsDatasheet

Consolidated electrical and interface specifications for every active part in the build.

Power Budget & Supply Sizing

Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.

LoadSupply railTypical current (mA)Notes
ESP32 DevKit V1 (ESP-WROOM-32)3.3 V logic / 5 V USB160Wi-Fi transmit bursts peak near 500 mA β€” size the regulator accordingly.
DS18B20 waterproof temperature probe3.0–5.5 V9Dozens can share one GPIO β€” you address them by ROM code.
SHT31-D temperature + humidity sensor2.4–5.5 V1.5The built-in heater burns off condensation β€” essential for outdoor or greenhouse use.
MH-Z19B NDIR COβ‚‚ sensor4.5–5.5 V60Disable auto-baseline calibration (ABC) for sealed rooms or it drifts to 400 ppm.
SX1278 LoRa 433 MHz module (Ra-02)3.3 V120Never power the radio without an antenna β€” the PA will destroy itself.
20 W 12 V polycrystalline solar panel12 V nominal1140Rated watts assume 1000 W/mΒ² β€” plan for 60–70 % of nameplate in real installs.
TP4056 Li-ion charger + DW01 protection4.5–5.5 V in1000Buy the version *with* protection ICs β€” the bare charger will over-discharge your cell.

Summed typical draw is 2490.5 mA. With a 1.5Γ— design margin the supply should deliver at least 3800 mA continuously at the stated rail voltage.

Software Requirements & Development Environment

Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.

  • Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
  • Add https://espressif.github.io/arduino-esp32/package_esp32_index.json under File β†’ Preferences β†’ Additional Board Manager URLs, then install esp32 from the Boards Manager.
  • Set the correct port under Tools β†’ Port. On Linux add yourself to the dialout group: sudo usermod -aG dialout $USER and log out and back in.
  • Open the Serial Monitor at 115200 baud β€” every sketch here logs its state there.
  • Keep File β†’ Preferences β†’ Show verbose output during: compilation switched on while you are debugging build errors.

Required libraries

LibraryWhy it is neededInstall
WiFi (ESP32 core) bundledStation/AP connection management for the ESP32.Bundled with the ESP32 Arduino core
OneWire + DallasTemperature 2.3.x / 3.9.xBus enumeration and conversion commands for DS18B20 probes.Library Manager β†’ "DallasTemperature" (pulls OneWire)
Adafruit Unified Sensor 1.1.xCommon sensor event abstraction; a dependency of most Adafruit drivers.Library Manager β†’ "Adafruit Unified Sensor"
LoRa (sandeepmistry) 0.8.0SX127x radio configuration, packet TX/RX and callbacks.Library Manager β†’ "LoRa" by Sandeep Mistry
ArduinoJson 7.xZero-allocation JSON serialisation and parsing.Library Manager β†’ "ArduinoJson" by Benoit Blanchon
Preferences (NVS) bundledWear-levelled key/value storage in ESP32 flash for settings.Bundled with the ESP32 core

Block Diagram

The block diagram shows the functional decomposition of the system β€” what senses, what decides, what acts, and where the data ends up.

Grain Silo Monitor β€” system block diagramFunctional block diagram of the Grain Silo Monitor system. In the grainTemp cableDS18B20 Γ—6 depthsHeadspace RHSHT31Headspace COβ‚‚MH-Z19 NDIROn the roofESP32sample + EMC + logicStoreflash log + baselinesLinkLoRa433/868 MHzOperatorBase stationshed gateway / phoneAlertlayer + actionrightrightnone
Grain Silo Monitor β€” system block diagram

Circuit Diagram & Wiring

Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.

Grain Silo Monitor β€” wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBDS18B20 chainGPIO 41-Wire data (4.7 kΞ©pull-up to 3V3)DS18B20 chain3V3Power (external, notparasitic, for along bus)SHT31GPIO 21/22IΒ²C headspacehumidity + tempMH-Z19 COβ‚‚GPIO 16/17UART NDIR COβ‚‚LoRa SX1276GPIO 18/19/23SPI radio busLoRa SX1276GPIO 5/14/2Chip-select, reset,RX-done IRQTP4056VIN / 3V3 regSolar-charged 18650supplySolar panelTP4056 IN6 V panel β†’ charger
Grain Silo Monitor β€” wiring schematic
PeripheralPeripheral pinController pinSignal
DS18B20 chainDQGPIO 41-Wire data (4.7 kΞ© pull-up to 3V3)
DS18B20 chainVDD3V3Power (external, not parasitic, for a long bus)
SHT31SDA/SCLGPIO 21/22IΒ²C headspace humidity + temp
MH-Z19 COβ‚‚TX/RXGPIO 16/17UART NDIR COβ‚‚
LoRa SX1276SCK/MISO/MOSIGPIO 18/19/23SPI radio bus
LoRa SX1276NSS/RST/DIO0GPIO 5/14/2Chip-select, reset, RX-done IRQ
TP4056OUTVIN / 3V3 regSolar-charged 18650 supply
Solar panel+/–TP4056 IN6 V panel β†’ charger

Wire one row at a time and tick it off β€” most "it does not work" reports trace back to a single swapped pair.

Wiring explanation

  • Only the probe cable and its gland go through the roof hatch; the ESP32, radio and battery live in an IP65 box bolted to the silo roof, out of the grain and the weather.
  • Give the DS18B20 bus a solid 4.7 kΞ© pull-up from data to 3V3 at the ESP32 end. One pull-up for the whole chain, not one per probe.
  • Power the DS18B20 chain from 3V3 (three-wire mode), not parasitically β€” parasitic power is unreliable over several metres of cable and many devices.
  • The MH-Z19 draws current in bursts when its lamp fires; power it from a stable 5 V (or its rated rail) and keep its ground short to the ESP32.
  • Route the COβ‚‚ sensor so it samples the headspace, not the outside air β€” but keep the electronics vented enough that condensation does not form inside the box.
A LoRa radio transceiver module
A LoRa radio module carries the depth profile across farm distances and through the silo's metal skin without Wi-Fi or mains. Photograph sourced from Wikimedia Commons β€” LoRa module.jpg. Reused under the licence stated on that page; please check it before republishing.

System Architecture

Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.

Grain Silo Monitor β€” architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) Β· DS18B20 waterproof temperature probe Β·SHT31-D temperature + humidity sensor Β· MH-Z19B NDIR COβ‚‚ sensorDriver layerwifi Β· onewire Β· unified Β· lorolibApplication logicsampling loop Β· filtering Β· thresholds Β· state machineTransport layerLoRa β†’ gateway β†’ MQTT Β· TLS Β· retry and backoffPresentation layerdashboard Β· mobile notifications Β· historical charts
Grain Silo Monitor β€” architecture stack

Working Principle

Grain spoilage is a coupled heat-and-moisture problem. A kernel at a given temperature and surrounding humidity holds a specific water content at equilibrium β€” its equilibrium moisture content. When the air around the grain is more humid than that equilibrium, the grain absorbs water; when drier, it releases it. Warm grain respires faster, respiration releases both heat and water, the water raises local humidity, higher humidity raises EMC, wetter grain respires faster still. That positive feedback is why a hot spot accelerates rather than settling down, and why catching it early β€” before the feedback dominates β€” matters so much.

Temperature at a single point tells you almost nothing, because grain is an excellent insulator: a hot spot 50 cm away can be invisible at the sensor while the average silo temperature barely moves. That is why the cable carries several sensors at different depths. The signal you look for is not an absolute temperature but a divergence: one depth pulling away from its neighbours, or one depth rising faster than the seasonal drift of the whole mass. A layer 4 Β°C above the two around it is a hot spot even if it is only 20 Β°C.

COβ‚‚ is the earliest and most sensitive channel. Biological respiration β€” grain, mould, and insects together β€” consumes oxygen and produces carbon dioxide continuously. Because the headspace is nearly closed, COβ‚‚ accumulates measurably from activity that is still far too small to move the temperature of a large thermal mass. A rising COβ‚‚ trend is the smoke alarm; the temperature cable tells you which room the fire is in.

The operator's levers are aeration (running a fan to push ambient air through the grain, cooling it and equalising moisture) and unloading (removing grain from the affected zone). The monitor's job is to tell them when and where: which depth is diverging, whether ambient conditions right now would help or harm if the fan runs (running a fan in humid weather can add moisture), and whether COβ‚‚ says the whole mass is trending the wrong way.

The maths behind it

Equilibrium moisture content (modified Henderson)

plainEquilibrium moisture content (modified Henderson)
A crop-specific model relates grain moisture m (% wet basis)
to air temperature T (Β°C) and relative humidity RH (fraction):

  1 βˆ’ RH = exp( βˆ’AΒ·(T + C)Β·m^B )

Solved for m:

  m = [ βˆ’ln(1 βˆ’ RH) / (AΒ·(T + C)) ]^(1/B)

A, B, C are tabulated per grain (wheat, maize, paddy…).
Example (wheat-like constants), T = 25 Β°C, RH = 0.65:
  gives m β‰ˆ 13–14% β€” the safe-storage range.
RH = 0.75 at the same T pushes m toward 15–16% β€” risk rises.

Hot-spot divergence test

plainHot-spot divergence test
For depth i with neighbours iβˆ’1, i+1:

  Ξ”_i = T_i βˆ’ Β½(T_{iβˆ’1} + T_{i+1})

Alarm if Ξ”_i > Ξ”_warn (e.g. 3 Β°C) sustained over N reads.

Also track rate of rise:
  dT_i/dt over 24 h; > 1 Β°C/day at one depth = developing
  hot spot even if the absolute temperature looks normal.

COβ‚‚ trend alarm

plainCOβ‚‚ trend alarm
Headspace COβ‚‚ rises with total respiration.
Compare a slow baseline to the current reading:

  baseline ← baseline + Ξ±Β·(COβ‚‚_now βˆ’ baseline)   (Ξ± small)
  alarm if COβ‚‚_now βˆ’ baseline > threshold (e.g. +400 ppm)
  or if COβ‚‚_now exceeds an absolute ceiling for stored grain.

The exponential baseline adapts to slow seasonal drift while
still catching a fast biological climb.

Program Flowchart

The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.

Grain Silo Monitor β€” firmware flowchartControl flow through the main program loop. Wake on scheduleRead all depths + RH + COβ‚‚Compute EMC from T + RHCOβ‚‚ or hot-spot ruletripped?Raise alert (layer + action)Log onlyRaise alert (layer + action)Log onlyTransmit profile over LoRaSleep until next interval
Grain Silo Monitor β€” firmware flowchart

Assembly Instructions

Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.

  1. Build the sensor cable

    Space the waterproof DS18B20 probes along the cable at the depths you want to monitor β€” for a typical farm silo, roughly every 0.5–1 m so the top, middle and bottom thirds each have coverage. The top third matters most: it is where moisture migrates and where hot spots most often start.

    Wire all probes in parallel on the three-wire bus (VDD, GND, DQ). Record each probe's unique 64-bit ROM address against its physical depth β€” the software needs this map to say "the 1.5 m layer is warming", not "sensor 3 is warming".

    Jacket the whole cable in a food-safe, abrasion-resistant sleeve. Grain flowing during loading and unloading exerts real force; a bare cable will chafe through in a season.

  2. Mount the roof enclosure

    Bolt the IP65 box to the silo roof beside the top hatch. Bring the sensor cable in through a gland; take the hanging weight on an eye-bolt or the gland's strain relief, never on the wire solder joints.

    Position the COβ‚‚ sensor so it samples headspace gas. If the box is fully sealed you will read box air, not silo air β€” provide a short vent tube or mount the sensor at the hatch.

    Angle the solar panel toward the sun and keep it clear of the hatch so opening the silo does not shade or knock it.

  3. Lower and secure the cable

    From the top hatch, lower the cable to the design depth with the deepest probe near β€” but not buried in β€” the silo floor cone. Mark the cable so re-installation next season lands the probes at the same depths.

    Seal the hatch around the cable as well as the silo design allows; a sealed headspace gives the truest COβ‚‚ signal and best represents the stored mass.

Step-by-Step Implementation Guide

Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.

  1. Enumerate and map the temperature bus

    Scan the 1-Wire bus and print every ROM address. Match each to a depth using the bench map you recorded, and store the ordered list in flash so reboots keep the same layer labels.

  2. Baseline the COβ‚‚ sensor

    Run the fresh-air (zero-point) calibration in clean outdoor air before installing, then let the adaptive software baseline track slow drift afterwards.

  3. Compute EMC and the alarms each cycle

    On each wake, read all depths, headspace RH/T and COβ‚‚; compute EMC; run the divergence, rate-of-rise and COβ‚‚ trend tests; then log and, if tripped, transmit an alert naming the layer and a suggested action.

    cppsilo-checks.ino
    // Called once per sampling cycle after all sensors are read.
    struct Layer { float depth_m; float tempC; };
    Layer layer[NUM_DEPTHS];
    
    // Grain equilibrium moisture content, modified-Henderson form.
    float emcPercent(float T, float rhFrac) {
      const float A = 2.3e-5, B = 2.16, C = 55.8;   // wheat-like; set per grain
      float num = -logf(1.0f - rhFrac);
      return powf(num / (A * (T + C)), 1.0f / B);
    }
    
    // Divergence of a depth from its two neighbours.
    bool hotSpot(int i, float warn) {
      if (i == 0 || i == NUM_DEPTHS - 1) return false;
      float d = layer[i].tempC - 0.5f * (layer[i-1].tempC + layer[i+1].tempC);
      return d > warn;
    }
    
    void evaluate(float headRH, float headT, float co2) {
      float emc = emcPercent(headT, headRH / 100.0f);
    
      int worst = -1; float worstDelta = 0;
      for (int i = 1; i < NUM_DEPTHS - 1; i++) {
        float d = layer[i].tempC - 0.5f*(layer[i-1].tempC + layer[i+1].tempC);
        if (d > worstDelta) { worstDelta = d; worst = i; }
      }
    
      co2Baseline += 0.02f * (co2 - co2Baseline);     // slow adaptive baseline
      bool co2Alarm = (co2 - co2Baseline) > 400.0f || co2 > CO2_CEILING;
    
      if (worst >= 0 && worstDelta > 3.0f) {
        alert("Hot spot at %.1f m: +%.1f C vs neighbours. Aerate/unload.",
              layer[worst].depth_m, worstDelta);
      }
      if (emc > 15.0f) alert("Grain EMC %.1f%% β€” too wet, ventilate in dry air.", emc);
      if (co2Alarm)    alert("CO2 rising (%.0f ppm) β€” biological activity. Inspect.", co2);
    }
    emcPercentTurns headspace temperature and humidity into the grain's equilibrium moisture β€” the number that decides whether storage is safe. The constants are grain-specific; swap them for wheat, maize or paddy.
    hotSpotA hot spot is a local divergence, not an absolute temperature, so each interior depth is compared with the mean of its two neighbours.
    co2Baseline += 0.02fAn exponential moving baseline follows slow seasonal drift while still letting a fast biological climb stand out above it.
    alert(Every alert names the affected layer and the action β€” aerate, ventilate, inspect β€” so the operator gets a decision, not a raw reading.
  4. Transmit and sleep

    Pack the depth profile, EMC, COβ‚‚ and any alerts into a compact LoRa packet, send it, then deep-sleep until the next interval. Hourly is plenty for a slow thermal mass; more often only if an alarm is active.

Complete Source Code

The listing below is complete and compiles as written β€” there are no elided sections. Read the annotations under each block before you upload it.

cppgrain-silo-monitor.ino
/* ═══════════════════════════════════════════════════════════════
   Grain Silo Monitor β€” ESP32, DS18B20 depth cable, CO2, LoRa, solar

   Samples grain temperature at several depths, headspace humidity and
   CO2, computes equilibrium moisture content, detects hot spots by
   neighbour-divergence and rate-of-rise, and reports over LoRa.
   ══════════════════════════════════════════════════════════════════ */

#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#include <Adafruit_SHT31.h>
#include <LoRa.h>
#include <SPI.h>
#include <Preferences.h>
#include <math.h>

#define PIN_OW      4        // DS18B20 1-Wire bus (4.7k pull-up to 3V3)
#define CO2_RX      16       // MH-Z19 TX -> ESP32 RX
#define CO2_TX      17       // MH-Z19 RX -> ESP32 TX
#define LORA_CS      5
#define LORA_RST    14
#define LORA_DIO0    2
#define NUM_DEPTHS   6
#define CO2_CEILING 3000.0f  // ppm absolute ceiling for stored grain
#define SLEEP_S     3600     // 1 h normal; shortened when alarmed

OneWire           ow(PIN_OW);
DallasTemperature grain(&ow);
Adafruit_SHT31    sht;
Preferences       prefs;
HardwareSerial    co2ser(2);

// depth[i] is the physical depth of the probe at bus index i, filled
// from the bench map stored in flash.
float depth_m[NUM_DEPTHS];
DeviceAddress addr[NUM_DEPTHS];
float co2Baseline;

/* ── CO2 read (MH-Z19 command frame) ─────────────────────────── */
float readCO2() {
  const uint8_t cmd[9] = {0xFF,0x01,0x86,0,0,0,0,0,0x79};
  co2ser.write(cmd, 9);
  uint8_t r[9]; unsigned long t0 = millis();
  int n = 0;
  while (n < 9 && millis() - t0 < 1000)
    if (co2ser.available()) r[n++] = co2ser.read();
  if (n == 9 && r[0] == 0xFF && r[1] == 0x86)
    return r[2] * 256 + r[3];
  return NAN;
}

/* ── EMC + alarms (see silo-checks) ──────────────────────────── */
float emcPercent(float T, float rhFrac) {
  const float A = 2.3e-5, B = 2.16, C = 55.8;
  return powf(-logf(1.0f - rhFrac) / (A * (T + C)), 1.0f / B);
}

void transmit(float *t, float headT, float headRH, float co2,
              float emc, int hotIdx, float hotDelta, bool co2Alarm) {
  LoRa.beginPacket();
  LoRa.print("{\"silo\":1,\"depths\":[");
  for (int i = 0; i < NUM_DEPTHS; i++) {
    LoRa.printf("%.1f", t[i]);
    if (i < NUM_DEPTHS - 1) LoRa.print(",");
  }
  LoRa.printf("],\"rh\":%.0f,\"co2\":%.0f,\"emc\":%.1f,"
              "\"hot_m\":%.1f,\"hot_d\":%.1f,\"co2_alarm\":%d}",
              headRH, co2, emc,
              hotIdx >= 0 ? depth_m[hotIdx] : -1.0f,
              hotDelta, co2Alarm ? 1 : 0);
  LoRa.endPacket();
}

void loadMap() {
  prefs.begin("silo", true);
  for (int i = 0; i < NUM_DEPTHS; i++) {
    char k[8]; snprintf(k, sizeof k, "d%d", i);
    depth_m[i] = prefs.getFloat(k, i * 0.75f);   // default even spacing
  }
  co2Baseline = prefs.getFloat("co2b", 450.0f);
  prefs.end();
}

void setup() {
  Serial.begin(115200);
  loadMap();
  grain.begin();
  grain.setResolution(12);
  Wire.begin(21, 22);
  sht.begin(0x44);
  co2ser.begin(9600, SERIAL_8N1, CO2_RX, CO2_TX);

  SPI.begin();
  LoRa.setPins(LORA_CS, LORA_RST, LORA_DIO0);
  if (!LoRa.begin(433E6)) Serial.println("LoRa init failed");
  LoRa.setSpreadingFactor(10);
  LoRa.setSignalBandwidth(125E3);

  // ── one sampling cycle ──
  grain.requestTemperatures();
  float t[NUM_DEPTHS];
  for (int i = 0; i < NUM_DEPTHS; i++)
    t[i] = grain.getTempCByIndex(i);

  float headT  = sht.readTemperature();
  float headRH = sht.readHumidity();
  float co2    = readCO2();
  float emc    = emcPercent(headT, headRH / 100.0f);

  int hotIdx = -1; float hotDelta = 0;
  for (int i = 1; i < NUM_DEPTHS - 1; i++) {
    float d = t[i] - 0.5f * (t[i-1] + t[i+1]);
    if (d > hotDelta) { hotDelta = d; hotIdx = i; }
  }

  if (!isnan(co2)) co2Baseline += 0.02f * (co2 - co2Baseline);
  bool co2Alarm = !isnan(co2) &&
                  ((co2 - co2Baseline) > 400.0f || co2 > CO2_CEILING);

  transmit(t, headT, headRH, co2, emc, hotIdx, hotDelta, co2Alarm);

  prefs.begin("silo", false);
  prefs.putFloat("co2b", co2Baseline);
  prefs.end();

  bool alarmed = (hotDelta > 3.0f) || (emc > 15.0f) || co2Alarm;
  uint32_t sleep_s = alarmed ? 600 : SLEEP_S;   // watch closely if alarmed
  esp_sleep_enable_timer_wakeup((uint64_t)sleep_s * 1000000ULL);
  esp_deep_sleep_start();
}

void loop() {}   // never reached; deep sleep restarts setup()
readCO2Sends the MH-Z19's 9-byte read command and decodes the response frame. A malformed or timed-out reply returns NAN so a bad read never poisons the baseline.
loadMapRestores the depth-to-bus-index map and the COβ‚‚ baseline from flash on every boot, so deep sleep does not lose the layer labels or the slow trend.
for (int i = 1; i < NUM_DEPTHS - 1Scans only interior depths for the largest neighbour-divergence, since the top and bottom probes have only one neighbour.
uint32_t sleep_s = alarmed ? 600A healthy silo is a slow system, so it sleeps an hour between reads; the moment anything trips, the interval drops to ten minutes to track the developing problem.

Configuration & Calibration

Configuration steps

  • Set the EMC constants (A, B, C) for the grain actually stored β€” wheat, maize and paddy have materially different curves.
  • Record the depth-to-address map in flash during commissioning so each layer is labelled by real depth.
  • Tune the divergence threshold (default 3 Β°C) and COβ‚‚ step (default +400 ppm) to your silo size and seal quality.
  • Choose the LoRa frequency legal in your region (433 MHz in much of Asia, 868 MHz in Europe) and match it at the base station.

Calibration procedure

An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.

  1. Temperature cable

    Before installing, bundle all probes together at room temperature and confirm they read within a few tenths of a degree of each other. A probe reading consistently high or low will fake a hot spot β€” record and subtract its offset.

  2. COβ‚‚ zero point

    Run the sensor's fresh-air calibration in clean outdoor air (β‰ˆ400 ppm) before installation. Repeat at the start of each storage season.

  3. EMC sanity check

    On loading day, take a grain sample to a moisture meter and compare with the computed EMC. If they disagree by more than a point, revisit the EMC constants for that grain.

Network Architecture & Connectivity

Grain Silo Monitor β€” network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsSilo nodeESP32 + LoRaNeighbour silossame designLoRa 433/868Shed gatewayLoRa β†’ MQTTMQTT 1883Broker + dashboardseason loggingDashboarddepth + COβ‚‚Phonealerts
Grain Silo Monitor β€” network topology

Communication protocol

Compact JSON over LoRa at SF10/125 kHz for range through the silo's metal skin and across farm distances. Hourly cadence keeps duty-cycle and power low; the interval shortens automatically while an alarm is active so a developing hot spot is seen in near-real time.

Topic / endpointDirectionPayload
grain/silo/1/profilenode β†’ brokerdepth temps, RH, COβ‚‚, EMC
grain/silo/1/alertnode β†’ brokerhot-spot / EMC / COβ‚‚ alerts
grain/silo/1/statusnode β†’ brokerbattery, RSSI, uptime

Message contract between the device and the broker.

Cloud platform configuration

The gateway publishes to an MQTT broker; a small dashboard trends each depth and the COβ‚‚ over the whole storage season, so you can see whether the mass actually cooled after loading or has been quietly drifting warmer.

Dashboard setup

A per-silo panel shows the depth column, EMC and COβ‚‚ updated each cycle; a season view overlays every depth so a slow warming trend at one layer stands out long before it becomes an alarm.

Mobile app integration

Alerts push to the operator's phone naming the silo, the affected layer and the recommended action β€” aerate, ventilate or inspect.

Security considerations

  • Include a per-node key and a rolling counter in each packet so a neighbour's identical hardware cannot spoof or replay readings.
  • Authenticate the broker so only the operator's dashboard subscribes to the silo data.
  • Alert on communication loss so a silently-dead node is noticed rather than assumed healthy.

Testing Procedure & Expected Output

Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop β€” the first failing step tells you exactly where to look.

TestWhat you should see
Bench-scan the 1-Wire busAll six ROM addresses enumerate; each maps to a known depth
Warm one probe by handThat depth reads a divergence; a hot-spot alert names its depth
Breathe near the COβ‚‚ sensorCOβ‚‚ jumps then decays; trend logic reacts, absolute ceiling respected
Compare EMC to a moisture meterAgreement within ~1 percentage point on the stored grain
Range-test the LoRa linkPackets received at the shed/base with acceptable RSSI
Run a 24 h solar cycleBattery recovers by day; no brown-out overnight

Bench-test checklist. If a row fails, stop and fix it before moving on.

Expected output

The base station shows a depth profile β€” a small column of temperatures top to bottom β€” plus headspace humidity, computed EMC and COβ‚‚, updated each cycle.

jsonlora-packet.json
{
  "silo": 1,
  "depths": [21.2, 21.5, 24.8, 21.9, 21.4, 21.1],
  "rh": 62,
  "co2": 690,
  "emc": 13.4,
  "hot_m": 1.5,
  "hot_d": 3.2,
  "co2_alarm": 0
}

Here depth index 2 (1.5 m) sits 3.2 Β°C above its neighbours β€” a developing hot spot flagged while the silo average still looks fine.

A photovoltaic solar panel in sunlight
A small solar panel keeps the monitor alive through a whole storage season with no wiring to the silo. Photograph sourced from Wikimedia Commons β€” Solar panel.jpg. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

One depth reads βˆ’127 Β°C

Likely cause. DS18B20 dropped off the bus (broken wire, bad joint, weak pull-up)

Fix. Check the 4.7 kΞ© pull-up and the probe's connections; flag that layer as faulted, do not average it in

All depths read the same, suspiciously

Likely cause. Only one probe enumerated; index-based reads repeat it

Fix. Verify the bus scan returns all addresses; use addresses, not just indices, when a probe may be missing

COβ‚‚ reads a flat 400 or 5000

Likely cause. Sensor still warming up, or wiring/UART fault

Fix. Allow the lamp warm-up time; confirm TX/RX are crossed and baud is 9600

EMC disagrees badly with a moisture meter

Likely cause. Wrong grain constants, or the sensor reads box air not headspace

Fix. Set A/B/C for the actual grain; ensure the RH/COβ‚‚ sensors sample the silo, not the enclosure

Constant false hot-spot alerts

Likely cause. One probe has an uncorrected offset

Fix. Apply the bench offset for that probe; raise the divergence threshold slightly

The sketch will not upload β€” "Failed to connect" or "avrdude: stk500_recv()"

Likely cause. The bootloader is not being reached: wrong port, wrong board, a serial monitor holding the port open, or a USB cable that only carries power.

Fix. Close every serial monitor, confirm Tools β†’ Board and Port, and swap to a known data-capable USB cable. On an ESP32 hold BOOT while the IDE prints "Connecting…", then release. If a peripheral is wired to the UART pins (GPIO 1/3 on ESP32, D0/D1 on Uno) unplug it β€” it fights the programmer.

The board resets in a loop, or the serial monitor prints "Brownout detector was triggered"

Likely cause. The supply cannot deliver peak current. Wi-Fi transmit bursts, relay coils and servos all pull far more than their average draw.

Fix. Power peripherals from a separate regulated supply with a common ground rather than from the board 5 V pin. Add a 470–1000 Β΅F electrolytic capacitor across the supply near the load, and use a real power adapter rather than a laptop USB port.

Serial monitor shows garbage characters

Likely cause. Baud rate mismatch between Serial.begin() and the monitor, or a floating/shared UART line.

Fix. Set the monitor to 115200 to match the sketch. If it still garbles, the crystal or the USB bridge is being confused by noise β€” shorten the cable and keep motor wiring away from the USB lead.

Wi-Fi connects but MQTT never does (state -2)

Likely cause. Wrong broker address or port, a firewall in the way, or the broker requiring credentials the sketch is not sending.

Fix. Test from a laptop on the same network first: mosquitto_sub -h <broker> -t "#" -v. If that works, the problem is on the device β€” check the IP literal, port 1883 (or 8883 for TLS), and that client.setServer() runs before connect(). PubSubClient state codes are documented in its header.

Readings arrive for a while and then stop

Likely cause. The Wi-Fi or MQTT session dropped and the sketch never reconnects, or the broker dropped the client on keep-alive timeout.

Fix. Never assume the link stays up. Check WiFi.status() and client.connected() at the top of every loop and reconnect with exponential backoff. Add a watchdog so a wedged network stack reboots the device instead of going silent.

Performance Optimisation

  • Deep-sleep between hourly reads; the DS18B20 conversion and COβ‚‚ lamp are the main awake-time costs.
  • Raise the sampling rate only while an alarm is active β€” that is when temporal resolution actually matters.
  • Keep LoRa at the lowest spreading factor that still reaches the gateway reliably; higher SF costs air-time and battery.
  • Cache the depth map and COβ‚‚ baseline in flash so a reboot never restarts the season's trend from scratch.
  • Replace every delay() with a millis() comparison β€” blocking delays are the single most common cause of dropped readings.
  • Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
  • Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
  • Use uint8_t / uint16_t where the range allows; on an 8-bit AVR a 32-bit add costs four times as much.
  • Batch several samples into one MQTT publish. Radio time, not CPU time, dominates the energy budget.
  • Set the MQTT keep-alive to a value that matches your reporting interval so the broker does not churn reconnections.
  • For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 Β΅A asleep, which is the difference between days and months of runtime.

Safety Precautions

  • Confined space: never enter a silo to install or service sensors. Grain engulfment and oxygen-deficient or COβ‚‚-rich atmospheres are lethal. Work from the top hatch only.
  • Follow your grain store's lockout rules before anyone works near augers, sweeps or aeration fans.
  • The monitor warns of spoilage risk; it does not replace a store's fire, fumigation and confined-space procedures.
  • Keep the lithium battery and charger in the roof enclosure, away from grain dust, which is combustible.
  • Lithium cells vent and burn when abused. Only use protected cells or a proper BMS, never charge below 0 Β°C, and never leave a charging pack unattended on a wooden desk.
  • Never power an RF module without its antenna fitted β€” the reflected power destroys the output stage. Check your local licence-free band and duty-cycle limits before transmitting.
  • Wear eye protection when soldering or cutting, and solder in a ventilated space β€” rosin flux fumes are a respiratory irritant.
  • Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
  • Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.

Maintenance

  • Re-run the COβ‚‚ fresh-air calibration at the start of each storage season.
  • Inspect the sensor cable jacket for grain-flow abrasion when the silo is empty.
  • Clean dust off the solar panel; a dusty panel is the most common cause of a mid-season brown-out.
  • Re-verify the depth map if the cable is ever removed and re-hung.
  • Re-check every screw terminal and header after the first week β€” thermal cycling loosens connections that felt tight on day one.
  • Log pack voltage. When resting voltage after a full charge drops below about 4.0 V, the cell is near end of life β€” replace it.
  • Wash the panel every few weeks in dusty conditions; a visible dust film costs 15–25 % of the harvest.
  • Keep the broker and dashboard containers patched, and rotate device credentials at least once a year.
  • Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware β€” not only in flash.
  • Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.

Future Improvements & Upgrades

A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.

  • Add a second COβ‚‚ sample point lower in the mass for a vertical activity gradient.
  • Drive an aeration-fan relay automatically when ambient air is dry and cool enough to help.
  • Estimate insect activity by separating COβ‚‚ diurnal rhythm from the slow mould baseline.
  • Fuse several seasons of profiles to predict safe storage duration for a given grain and moisture.
  • Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
  • Add over-the-air firmware updates so you never have to physically reach a deployed node again.
  • Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
  • Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
  • Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
  • Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.

Frequently Asked Questions

Why not just one temperature sensor in the middle?

Grain insulates so well that a hot spot half a metre away is invisible to a single sensor. Several depths let you see divergence, which is the actual early signal.

Is COβ‚‚ really necessary if I have temperature?

COβ‚‚ moves first. Respiration produces measurable COβ‚‚ long before it warms a large thermal mass, so it buys you days of early warning that temperature alone cannot.

Will running the aeration fan always help?

No β€” pushing warm, humid air through cool grain adds moisture. That is exactly why the monitor reports ambient conditions and EMC, so you aerate when the air will actually dry and cool the grain.

How long does it run without mains?

A small solar panel and one 18650 comfortably cover a storage season at hourly sampling, because the device sleeps almost all the time.

Can one gateway serve several silos?

Yes. Each node carries its own ID and key; the LoRa gateway collects them all and forwards to your dashboard.

References & Learning Resources

These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.

  1. FAO β€” Grain storage techniques and stored-grain ecologyFAO
  2. Modified Henderson EMC model for cereal grainsReference
  3. DS18B20 programmable resolution 1-Wire digital thermometer (datasheet)Analog Devices
  4. MH-Z19 NDIR COβ‚‚ sensor β€” application notesWinsen
  5. OSHA / confined-space grain handling safetyOSHA