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.
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
| Setting | How it is used |
|---|---|
| On-farm storage | A farmer holding wheat, maize or paddy for a better price weeks or months after harvest, protecting the crop from silent spoilage. |
| Co-operative / FPO warehouses | Village-level aggregators storing many members' grain, where one undetected hot spot means many families' losses and disputes. |
| Seed storage | Seed viability collapses with heat and moisture; continuous monitoring protects germination rate, which is the seed's entire value. |
| Procurement / mandi godowns | Government 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
| Attribute | Value |
|---|---|
| Difficulty level | Intermediate |
| Estimated completion time | 10β16 hours |
| Indicative build cost | βΉ3,200 β βΉ4,200 |
| Primary discipline | Agriculture |
| Reference platform | ESP32 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.
| Component | Key specification | Qty | Approx. 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 DAC | 1 | βΉ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 ID | 6 | βΉ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 heater | 1 | βΉ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 output | 1 | βΉ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βSF12 | 1 | βΉ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 frame | 1 | βΉ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 protection | 1 | βΉ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 discharge | 1 | βΉ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 m | 1 | βΉ900 |
| Weatherproof field enclosure Electronics stay outside the grain; only probes go in | IP65, UV-stable, cable glands, mounts on silo roof | 1 | βΉ450 |
| Grain-safe cable gland / eye-bolt | Seals the probe cable at the roof hatch, takes the hanging weight | 1 | βΉ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
| Part | Specification | Supply | Interface | Reference |
|---|---|---|---|---|
| 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 DAC | 3.3 V logic / 5 V USB | UART, SPI, IΒ²C, IΒ²S, CAN, PWM | Datasheet |
| DS18B20 waterproof temperature probe | β55 to +125 Β°C, Β±0.5 Β°C from β10 to +85 Β°C, 9β12-bit resolution, unique 64-bit ROM ID | 3.0β5.5 V | 1-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 heater | 2.4β5.5 V | IΒ²C (0x44/0x45) | Datasheet |
| MH-Z19B NDIR COβ sensor | 0β5000 ppm Β±(50 ppm + 5 %), NDIR, 60 s warm-up, UART + PWM output | 4.5β5.5 V | UART 9600 8N1, PWM | Datasheet |
| SX1278 LoRa 433 MHz module (Ra-02) | β148 dBm sensitivity, +20 dBm output, up to 10 km line of sight, SF7βSF12 | 3.3 V | SPI | Datasheet |
| 20 W 12 V polycrystalline solar panel | Vmp 17.5 V, Imp 1.14 A, Voc 21.6 V, 350 Γ 290 mm, aluminium frame | 12 V nominal | MC4 / screw terminals | Datasheet |
| TP4056 Li-ion charger + DW01 protection | 1 A programmable CC/CV charge to 4.2 V Β±1 %, over-discharge and short protection | 4.5β5.5 V in | micro-USB / pads | Datasheet |
| 18650 Li-ion cell 3400 mAh + holder | 3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge | 3.0β4.2 V | Holder / spot-welded tabs | Datasheet |
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.
| Load | Supply rail | Typical current (mA) | Notes |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | 3.3 V logic / 5 V USB | 160 | Wi-Fi transmit bursts peak near 500 mA β size the regulator accordingly. |
| DS18B20 waterproof temperature probe | 3.0β5.5 V | 9 | Dozens can share one GPIO β you address them by ROM code. |
| SHT31-D temperature + humidity sensor | 2.4β5.5 V | 1.5 | The built-in heater burns off condensation β essential for outdoor or greenhouse use. |
| MH-Z19B NDIR COβ sensor | 4.5β5.5 V | 60 | Disable auto-baseline calibration (ABC) for sealed rooms or it drifts to 400 ppm. |
| SX1278 LoRa 433 MHz module (Ra-02) | 3.3 V | 120 | Never power the radio without an antenna β the PA will destroy itself. |
| 20 W 12 V polycrystalline solar panel | 12 V nominal | 1140 | Rated watts assume 1000 W/mΒ² β plan for 60β70 % of nameplate in real installs. |
| TP4056 Li-ion charger + DW01 protection | 4.5β5.5 V in | 1000 | Buy 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.jsonunder 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
dialoutgroup:sudo usermod -aG dialout $USERand 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
| Library | Why it is needed | Install |
|---|---|---|
| WiFi (ESP32 core) bundled | Station/AP connection management for the ESP32. | Bundled with the ESP32 Arduino core |
| OneWire + DallasTemperature 2.3.x / 3.9.x | Bus enumeration and conversion commands for DS18B20 probes. | Library Manager β "DallasTemperature" (pulls OneWire) |
| Adafruit Unified Sensor 1.1.x | Common sensor event abstraction; a dependency of most Adafruit drivers. | Library Manager β "Adafruit Unified Sensor" |
| LoRa (sandeepmistry) 0.8.0 | SX127x radio configuration, packet TX/RX and callbacks. | Library Manager β "LoRa" by Sandeep Mistry |
| ArduinoJson 7.x | Zero-allocation JSON serialisation and parsing. | Library Manager β "ArduinoJson" by Benoit Blanchon |
| Preferences (NVS) bundled | Wear-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.
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.
| Peripheral | Peripheral pin | Controller pin | Signal |
|---|---|---|---|
| DS18B20 chain | DQ | GPIO 4 | 1-Wire data (4.7 kΞ© pull-up to 3V3) |
| DS18B20 chain | VDD | 3V3 | Power (external, not parasitic, for a long bus) |
| SHT31 | SDA/SCL | GPIO 21/22 | IΒ²C headspace humidity + temp |
| MH-Z19 COβ | TX/RX | GPIO 16/17 | UART NDIR COβ |
| LoRa SX1276 | SCK/MISO/MOSI | GPIO 18/19/23 | SPI radio bus |
| LoRa SX1276 | NSS/RST/DIO0 | GPIO 5/14/2 | Chip-select, reset, RX-done IRQ |
| TP4056 | OUT | VIN / 3V3 reg | Solar-charged 18650 supply |
| Solar panel | +/β | TP4056 IN | 6 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.
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.
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)
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
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
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.
Assembly Instructions
Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.
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.
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.
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.
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.
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.
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.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.
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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()
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.
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.
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.
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
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 / endpoint | Direction | Payload |
|---|---|---|
grain/silo/1/profile | node β broker | depth temps, RH, COβ, EMC |
grain/silo/1/alert | node β broker | hot-spot / EMC / COβ alerts |
grain/silo/1/status | node β broker | battery, 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.
| Test | What you should see |
|---|---|
| Bench-scan the 1-Wire bus | All six ROM addresses enumerate; each maps to a known depth |
| Warm one probe by hand | That depth reads a divergence; a hot-spot alert names its depth |
| Breathe near the COβ sensor | COβ jumps then decays; trend logic reacts, absolute ceiling respected |
| Compare EMC to a moisture meter | Agreement within ~1 percentage point on the stored grain |
| Range-test the LoRa link | Packets received at the shed/base with acceptable RSSI |
| Run a 24 h solar cycle | Battery 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.
{
"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.
Troubleshooting: Common Errors & Fixes
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 amillis()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_twhere 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
References & Learning Resources
These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.