Siddhant Kumar
Project 035 Β· Agriculture

Beehive Health Monitor.

Weighs a beehive continuously and listens to its temperature, humidity and sound so a beekeeper reads the colony's state without opening it.

Intermediate 12–18 hours 36 min read SensorsApiaryCloud
Jump to source Bill of materials
Beehive Health Monitor β€” reference build illustration MCU VCC Β· GND Β· SIG Β· NC
Difficulty
Intermediate
Build time
12–18 hours
Indicative cost
β‚Ή3,800 – β‚Ή5,200
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Agriculture
Last updated
28 July 2026
Contents β€” 26 sections

Project Overview

Weighs a beehive continuously and listens to its temperature, humidity and sound so a beekeeper reads the colony's state without opening it.

Every time a beekeeper opens a hive to inspect it, they chill the brood, crush a few bees, provoke the colony, and interrupt the very work they are trying to protect. Yet the colony is constantly broadcasting its state in signals you never see from the outside: its weight climbs during a nectar flow and falls when foragers cannot fly or when stores are being eaten; its brood-nest temperature is held near 35 Β°C with astonishing precision whenever there is brood to raise; its sound changes character before swarming and when the colony goes queenless. This monitor turns the hive into an instrument so the beekeeper reads those signals from a phone and only opens the hive when the data says something is worth checking.

A load cell under the hive (or a framed scale platform) measures weight to the tens of grams, revealing the daily rhythm of foraging and the slow arc of the honey flow. An SHT31 in the brood area tracks temperature and humidity; a stable 34–35 Β°C signals healthy, actively-thermoregulated brood, while a sudden loss of regulation can mean a failing or absent queen. A microphone captures the hive's acoustic signature, whose changes precede swarming and mark queenlessness. An ESP32 logs all of it, and because apiaries sit in fields far from power and Wi-Fi, the whole thing runs on solar and reports over LoRa.

The result is a hive that tells its own story: "gained 1.8 kg today β€” good flow", "brood temperature slipping, inspect the queen", "pre-swarm acoustic signature rising". It reduces needless inspections, catches problems days earlier than a monthly check would, and β€” for a beekeeper running many hives across many sites β€” turns a guessing game into a prioritised list of which colonies actually need a visit.

A photovoltaic solar panel in sunlight
A solar panel and battery let the hive monitor run a full season in a remote apiary with no mains power. Photograph sourced from Wikimedia Commons β€” Solar panel.jpg. Reused under the licence stated on that page; please check it before republishing.

What this project does

  • Weighs the hive continuously to tens-of-grams resolution (load cell + HX711)
  • Tracks brood-area temperature and humidity, the core sign of colony health
  • Captures the hive's acoustic signature to flag pre-swarm and queenless states
  • Separates daily foraging rhythm from the slow honey-flow trend in the weight
  • Runs on solar + battery in a remote apiary with no mains or Wi-Fi
  • Reports over long-range LoRa to a base station or phone
  • Alerts on abnormal weight loss, lost thermoregulation and swarm-signature changes

Real-World Applications

SettingHow it is used
Hobby and sideline beekeepingA beekeeper with a handful of hives watching each colony's weight and brood health remotely, opening a hive only when the data warrants.
Commercial / migratory apiariesHundreds of hives across many sites, where a scale on each colony turns hive management into a prioritised route rather than a blind round.
Pollination servicesGrowers renting hives for pollination can verify colony strength and activity objectively during the contract.
Research and conservationLong-term weight, temperature and acoustic records for studying forage availability, colony collapse and climate effects on bees.

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

Features & Capabilities

  • Hive-scale weight with temperature compensation of the load cell
  • Brood thermoregulation as a direct, non-invasive queen-health proxy
  • Acoustic features (band energy) for swarm and queenless detection
  • Nectar-flow vs consumption separated from the weight signal
  • Season-long solar operation with deep sleep between reads
  • LoRa link for apiaries far from any network
  • Fewer, better-timed inspections β€” the colony is disturbed only when needed

Difficulty, Time & Required Skills

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

Skills you should have (or will pick up)

  • Using a load cell with an HX711 24-bit ADC, including tare and calibration
  • Temperature-compensating a weight signal
  • Reading an IΒ²S/analogue microphone and computing simple band-energy features
  • Interpreting brood thermoregulation and hive acoustics
  • LoRa + solar design for remote, season-long 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
5 kg load cell + HX711 24-bit ADC
Mechanical mounting dominates accuracy β€” bolt it to a rigid plate, not plastic.
Strain-gauge bridge, 1.0 mV/V output, HX711 128Γ— gain, 10/80 SPS1β‚Ή320
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
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 ID1β‚Ή160
INMP441 IΒ²S MEMS microphone
Digital output means no analogue noise pickup β€” far better than an MAX9814 for keyword spotting.
61 dB SNR, βˆ’26 dBFS sensitivity, 60 Hz–15 kHz, 24-bit IΒ²S output1β‚Ή220
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
Hive scale frame + HX711
Single bar under a corner + pivot, or four cells for full support
Load cell(s) in a platform sized to the hive footprint; 200 kg bar or 4Γ— 50 kg1β‚Ή1,100
Vented probe cageProtects the SHT31 in the brood box from propolis while letting air through1β‚Ή90
Weatherproof enclosureIP65 for the electronics, mounted on or beside the hive stand1β‚Ή420

Estimated total: β‚Ή5,555, 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
5 kg load cell + HX711 24-bit ADCStrain-gauge bridge, 1.0 mV/V output, HX711 128Γ— gain, 10/80 SPS2.6–5.5 V2-wire serial (bit-banged)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
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
INMP441 IΒ²S MEMS microphone61 dB SNR, βˆ’26 dBFS sensitivity, 60 Hz–15 kHz, 24-bit IΒ²S output1.8–3.3 VIΒ²SDatasheet
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.
5 kg load cell + HX711 24-bit ADC2.6–5.5 V1.5Mechanical mounting dominates accuracy β€” bolt it to a rigid plate, not plastic.
SHT31-D temperature + humidity sensor2.4–5.5 V1.5The built-in heater burns off condensation β€” essential for outdoor or greenhouse use.
DS18B20 waterproof temperature probe3.0–5.5 V1.5Dozens can share one GPIO β€” you address them by ROM code.
INMP441 IΒ²S MEMS microphone1.8–3.3 V1.4Digital output means no analogue noise pickup β€” far better than an MAX9814 for keyword spotting.
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 2425.9 mA. With a 1.5Γ— design margin the supply should deliver at least 3700 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
HX711 0.7.xBit-banged 24-bit ADC read with tare and calibration factor.Library Manager β†’ "HX711" by Bogdan Necula
Adafruit Unified Sensor 1.1.xCommon sensor event abstraction; a dependency of most Adafruit drivers.Library Manager β†’ "Adafruit Unified Sensor"
OneWire + DallasTemperature 2.3.x / 3.9.xBus enumeration and conversion commands for DS18B20 probes.Library Manager β†’ "DallasTemperature" (pulls OneWire)
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.

Beehive Health Monitor β€” system block diagramFunctional block diagram of the Beehive Health Monitor system. The hive speaksWeightload cell + HX711Brood T/RHSHT31SoundINMP441 IΒ²SAmbient TDS18B20InterpretESP32compensate + featuresTrendsflow, brood, swarmLinkLoRato apiary baseBeekeeperDashboardper-hive storyAlertwhich hive to openrightrightnone
Beehive Health 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.

Beehive Health 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 USBHX711 (load cell)GPIO 16/4Weight ADC (24-bit)SHT31GPIO 21/22Brood temp +humidity (IΒ²C)DS18B20GPIO 17Ambient temp(load-cellcompensation)INMP441 micGPIO 33/25/32IΒ²S hive audioLoRa SX1276GPIO 18/19/23SPI radio busLoRa SX1276GPIO 5/14/2Chip-select, reset,IRQTP4056VIN / 3V3 regSolar-charged 18650supplySolar panelTP4056 IN6 V panel β†’ charger
Beehive Health Monitor β€” wiring schematic
PeripheralPeripheral pinController pinSignal
HX711 (load cell)DT/SCKGPIO 16/4Weight ADC (24-bit)
SHT31SDA/SCLGPIO 21/22Brood temp + humidity (IΒ²C)
DS18B20DQGPIO 17Ambient temp (load-cell compensation)
INMP441 micSD/WS/SCKGPIO 33/25/32IΒ²S hive audio
LoRa SX1276SCK/MISO/MOSIGPIO 18/19/23SPI radio bus
LoRa SX1276NSS/RST/DIO0GPIO 5/14/2Chip-select, reset, 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

  • Mount the load cell so the hive's weight is carried cleanly through it β€” a single bar under one edge with a pivot at the other, or four cells at the corners for a heavy hive.
  • Run the HX711 close to the load cell and keep its excitation/signal leads short; it is a sensitive 24-bit converter and long analogue leads pick up noise.
  • Give the ambient DS18B20 its own spot in shade near the hive so it measures the temperature the load cell actually sees, for compensation.
  • The INMP441 is an IΒ²S MEMS mic; wire SD/WS/SCK to the IΒ²S pins and place it against the hive body where it hears the cluster, not the wind.
  • Keep the electronics box off the hive's vibration path where practical so bee activity and wind do not shake the enclosure and the mic mount.
An ESP32 development board with the ESP-WROOM-32 module and USB connector
ESP32 module β€” reads the hive scale, brood sensors and microphone, fuses them, 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.

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.

Beehive Health Monitor β€” architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) Β· SHT31-D temperature + humidity sensor Β·DS18B20 waterproof temperature probeDriver layerwifi Β· hx711 Β· unified Β· onewireApplication logicsampling loop Β· filtering Β· thresholds Β· state machineTransport layerLoRa β†’ apiary gateway β†’ dashboard Β· TLS Β· retry and backoffPresentation layerdashboard Β· mobile notifications Β· historical charts
Beehive Health Monitor β€” architecture stack

Working Principle

Weight is the richest single signal a hive gives. Over a day it traces the colony's foraging: it dips in the morning as foragers leave, climbs through the day as they return laden, and settles overnight. Subtract that daily rhythm and the residual trend is the honey flow β€” kilograms gained over a good week, or a steady loss when nectar is scarce and the colony is eating its stores. A sudden step down can mean a swarm has left (taking half the bees and some honey) or a robbing event; a sudden step up is usually the beekeeper adding a box. The load cell must be temperature-compensated, because the metal's response drifts with heat and an uncompensated scale would fake a daily weight cycle that is really just the sun warming the sensor.

Brood temperature is the colony's vital sign. Honeybees hold the brood nest at roughly 34–35 Β°C with remarkable stability whenever there is brood to raise, spending real energy to do it. As long as that regulation holds, the colony has the population and the will to keep brood warm β€” a strong indirect sign of a laying queen and a healthy workforce. When the brood-area temperature starts drifting with ambient, or collapses, it often means the colony has lost its ability or reason to thermoregulate: a dead or failing queen, a collapsed population, or a colony that has already absconded. That loss of regulation is one of the earliest remote signs that something is seriously wrong.

Sound carries information nothing else does. A queenright colony has a characteristic hum; a queenless one develops a rising, plaintive "roar", and the days before swarming bring changes in the colony's acoustic energy and the piping of rival queens. You do not need full spectral analysis on a microcontroller to use this β€” computing the energy in a few frequency bands and watching how their ratios move over days captures much of the swarm and queenless signal cheaply. The monitor is not trying to diagnose from sound alone; it is raising a flag that, combined with weight and temperature, tells the beekeeper which hive deserves a look.

The value of putting these three signals together is that each disambiguates the others. A weight drop plus a lost brood temperature plus a queenless acoustic signature is a confident "this colony is in trouble". A weight drop with healthy brood temperature and a normal hum is probably just poor forage weather. That fusion β€” done on-device, reported compactly over LoRa β€” is what turns raw sensors into a decision about whether to drive out and open the hive.

The maths behind it

Temperature-compensated weight

plainTemperature-compensated weight
Raw load-cell output drifts with temperature. Model the
drift as roughly linear and correct it:

  W_corr = W_raw βˆ’ k_T Β· (T_amb βˆ’ T_cal)

k_T is the cell/frame drift coefficient (kg per Β°C),
found by watching the empty scale over a day/night cycle.
T_cal is the temperature at which tare was taken.
Without this, a warm afternoon fakes a weight change.

Daily rhythm vs honey-flow trend

plainDaily rhythm vs honey-flow trend
Split the weight series into a fast daily part and a slow
trend:

  trend_t = trend_{tβˆ’1} + Ξ²Β·(W_corr βˆ’ trend_{tβˆ’1})   (Ξ² small)
  daily   = W_corr βˆ’ trend_t

trend rising over days  β†’ nectar flow (honey gain)
trend falling steadily  β†’ dearth / consumption
sharp step down in trend β†’ swarm or robbing event.

Brood thermoregulation index

plainBrood thermoregulation index
Compare brood temperature to ambient:

  reg = (T_brood βˆ’ T_amb) held while T_brood β‰ˆ 35 Β°C

Healthy: T_brood stable near 34–35 Β°C, reg large and steady
Warning: T_brood tracks T_amb (reg β†’ small) or falls
         well below 34 Β°C β†’ possible queen/population loss.

Acoustic band-energy features

plainAcoustic band-energy features
From a short audio capture, compute energy in bands:

  E_low  (~100–300 Hz), E_mid (~300–600 Hz), E_high (>600 Hz)
  ratio  = E_high / E_low

Rising ratio / roar over days can accompany queenlessness;
pre-swarm periods show characteristic shifts and piping.
Use trends, not one reading, and always with weight + temp.

Program Flowchart

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

Beehive Health Monitor β€” firmware flowchartControl flow through the main program loop. Wake on scheduleRead weight (temp-compensated)Read brood T/RH + ambientRecord short audio, computeband energyBrood regulation lost orswarm signature?Flag colony for inspectionUpdate trendsFlag colony for inspectionUpdate trendsTransmit over LoRaSleep until next interval
Beehive Health 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 hive scale

    Fit the load cell(s) into a flat platform sized to the hive footprint. For a light single-box hive one 200 kg bar under a corner with a pivot opposite can work; for a full production hive, four 50 kg cells at the corners share the load and read most accurately.

    Wire the cell(s) to the HX711 with short leads and mount the HX711 in the electronics box, close to the platform.

    Set the hive on the platform level; a tilted hive puts uneven load on the cell and both reads badly and shortens its life.

  2. Place the internal sensors

    Slide the SHT31 in its vented cage into the brood area, positioned where the cluster keeps it β€” near the centre of the brood nest β€” but where you can retrieve it. Bees will propolise it over time; the cage slows this.

    Mount the INMP441 against the hive body so it hears the cluster. Isolate it from wind and rain but keep an acoustic path to the interior.

  3. Set up power and radio

    Mount the IP65 box on or beside the hive stand, angle the solar panel to the sun, and route the LoRa antenna clear of metal.

    Place the ambient DS18B20 in shade near the hive so the weight compensation uses the temperature the scale actually experiences.

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. Tare and calibrate the scale

    Tare the empty platform, then place a known weight and set the HX711 scale factor so the reading matches. Record the ambient temperature at tare for the compensation baseline.

  2. Learn the brood and acoustic baselines

    Over the first days, record the normal brood temperature band and the normal acoustic band ratios for this colony, so later alerts are relative to this hive rather than a textbook number.

  3. Compute features and fuse them

    Each cycle: temperature-compensate the weight, update the daily/trend split, read brood T/RH, capture a short audio clip and compute band energies, then combine the three into a health verdict.

    cpphive-features.ino
    struct Hive { float weight, trend, broodT, ambT, ratio; };
    
    // Temperature-compensated weight from the HX711 reading.
    float compWeight(float raw, float ambT) {
      return raw - K_T * (ambT - T_CAL);          // K_T kg/degC, from calibration
    }
    
    // Slow trend (honey flow) separated from the daily foraging rhythm.
    void updateTrend(Hive &h, float w) {
      h.trend += 0.02f * (w - h.trend);           // slow EMA
    }
    
    // Combine the three channels into a colony verdict.
    const char* verdict(const Hive &h, float ratioBase, float trendPrev) {
      bool broodLost = (h.broodT < 32.0f) ||
                       (fabsf(h.broodT - h.ambT) < 3.0f);   // tracks ambient
      bool swarmSig  = (h.ratio > 1.4f * ratioBase);
      bool stepDown  = (trendPrev - h.trend) > 1.0f;        // sudden kg loss
    
      if (broodLost && (swarmSig || stepDown)) return "CRITICAL: inspect now";
      if (broodLost)                           return "WARN: brood cooling";
      if (swarmSig)                            return "WATCH: swarm signature";
      if (stepDown)                            return "WATCH: sudden weight loss";
      return "OK";
    }
    compWeightRemoves the load cell's temperature drift so a warm afternoon does not masquerade as the colony gaining or losing weight.
    updateTrendA slow exponential average strips the daily foraging wobble and leaves the honey-flow trend that actually matters week to week.
    bool broodLostBrood trouble shows up either as an outright low temperature or as the brood temperature collapsing toward ambient β€” the colony no longer regulating.
    if (broodLost && (swarmSig || stepDown))The signals are fused: a cold brood nest together with a swarm signature or a sudden weight drop is a confident call to drive out and open the hive.
  4. Transmit and sleep

    Send the compensated weight, trend, brood T/RH, acoustic ratio and verdict over LoRa, then deep-sleep. A read every 15–30 minutes captures the daily curve without draining the battery.

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.

cppbeehive-health-monitor.ino
/* ═══════════════════════════════════════════════════════════════
   Beehive Health Monitor β€” ESP32, load cell, brood T/RH, mic, LoRa

   Weighs the hive (temperature-compensated), tracks brood
   thermoregulation, extracts acoustic band-energy features, fuses the
   three into a colony verdict, and reports over LoRa on solar power.
   ══════════════════════════════════════════════════════════════════ */

#include <HX711.h>
#include <Wire.h>
#include <Adafruit_SHT31.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <driver/i2s.h>
#include <LoRa.h>
#include <SPI.h>
#include <Preferences.h>
#include <math.h>

#define HX_DT     16
#define HX_SCK     4
#define OW_PIN    17
#define I2S_SD    33
#define I2S_WS    25
#define I2S_SCK   32
#define LORA_CS    5
#define LORA_RST  14
#define LORA_DIO0  2

#define SLEEP_S    1200          // 20 min between reads

HX711             scale;
Adafruit_SHT31    sht;
OneWire           ow(OW_PIN);
DallasTemperature ambient(&ow);
Preferences       prefs;

// Persisted state (survives deep sleep).
RTC_DATA_ATTR float trend = 0, trendPrev = 0, ratioBase = 0;
RTC_DATA_ATTR bool  primed = false;

float K_T, T_CAL, HX_SCALE;      // calibration constants from flash

/* ── I2S mic: capture a block, return band-energy ratio ──────── */
float acousticRatio() {
  i2s_config_t cfg = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = 8000,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
    .communication_format = I2S_COMM_FORMAT_STAND_I2S,
    .intr_alloc_flags = 0, .dma_buf_count = 4, .dma_buf_len = 256 };
  i2s_pin_config_t pins = { I2S_SCK, I2S_WS, I2S_PIN_NO_CHANGE, I2S_SD };
  i2s_driver_install(I2S_NUM_0, &cfg, 0, NULL);
  i2s_set_pin(I2S_NUM_0, &pins);

  const int N = 1024; int32_t buf[256]; size_t br;
  double eLow = 0, eHigh = 0; int got = 0;
  // Crude band split via a one-pole high-pass to separate low/high energy.
  int32_t prev = 0; double hp = 0;
  while (got < N) {
    i2s_read(I2S_NUM_0, buf, sizeof buf, &br, 100);
    int n = br / 4;
    for (int i = 0; i < n && got < N; i++, got++) {
      double x = buf[i] >> 8;                 // 24-bit sample
      hp = 0.9 * (hp + x - prev); prev = x;    // high-pass
      eHigh += hp * hp;
      eLow  += (x - hp) * (x - hp);
    }
  }
  i2s_driver_uninstall(I2S_NUM_0);
  if (eLow < 1) return 0;
  return (float)(eHigh / eLow);
}

void transmit(float w, float broodT, float rh, float ambT,
              float ratio, const char *v) {
  LoRa.beginPacket();
  LoRa.printf("{\"hive\":1,\"w\":%.2f,\"trend\":%.2f,\"broodT\":%.1f,"
              "\"rh\":%.0f,\"ambT\":%.1f,\"ratio\":%.2f,\"v\":\"%s\"}",
              w, trend, broodT, rh, ambT, ratio, v);
  LoRa.endPacket();
}

const char* verdict(float broodT, float ambT, float ratio) {
  bool broodLost = (broodT < 32.0f) || (fabsf(broodT - ambT) < 3.0f);
  bool swarmSig  = ratioBase > 0 && ratio > 1.4f * ratioBase;
  bool stepDown  = (trendPrev - trend) > 1.0f;
  if (broodLost && (swarmSig || stepDown)) return "CRITICAL";
  if (broodLost) return "WARN_BROOD";
  if (swarmSig)  return "WATCH_SWARM";
  if (stepDown)  return "WATCH_WEIGHT";
  return "OK";
}

void loadCal() {
  prefs.begin("hive", true);
  K_T      = prefs.getFloat("kT", 0.0f);
  T_CAL    = prefs.getFloat("tcal", 25.0f);
  HX_SCALE = prefs.getFloat("hxs", 1.0f);
  prefs.end();
}

void setup() {
  Serial.begin(115200);
  loadCal();

  scale.begin(HX_DT, HX_SCK);
  scale.set_scale(HX_SCALE);
  Wire.begin(21, 22);
  sht.begin(0x44);
  ambient.begin();

  float raw    = scale.get_units(10);
  ambient.requestTemperatures();
  float ambT   = ambient.getTempCByIndex(0);
  float w      = raw - K_T * (ambT - T_CAL);   // temp-compensated weight
  float broodT = sht.readTemperature();
  float rh     = sht.readHumidity();
  float ratio  = acousticRatio();

  trendPrev = trend;
  trend += 0.02f * (w - trend);
  if (!primed) { trend = w; ratioBase = ratio; primed = true; }
  else if (ratioBase > 0) ratioBase += 0.05f * (ratio - ratioBase);

  const char *v = verdict(broodT, ambT, ratio);

  SPI.begin();
  LoRa.setPins(LORA_CS, LORA_RST, LORA_DIO0);
  LoRa.begin(433E6);
  LoRa.setSpreadingFactor(10);
  transmit(w, broodT, rh, ambT, ratio, v);

  esp_sleep_enable_timer_wakeup((uint64_t)SLEEP_S * 1000000ULL);
  esp_deep_sleep_start();
}

void loop() {}   // deep sleep restarts setup()
RTC_DATA_ATTR float trendThe honey-flow trend and acoustic baseline live in RTC memory so they persist across deep sleep β€” the colony's multi-day story is not reset every 20 minutes.
float acousticRatio()Captures a short IΒ²S audio block and splits it into low- and high-frequency energy with a cheap one-pole filter, yielding a single ratio that tracks swarm/queenless acoustic shifts without a full FFT.
float w = raw - K_T * (ambT - T_CAL)Applies the temperature compensation at the point of measurement, so every transmitted weight is already corrected for the day's heat.
if (!primed)On the very first wake the trend and acoustic baseline are seeded from the current reading, so early cycles do not fire false alerts before the colony's normal is learned.
const char *v = verdict(Fuses weight trend, brood thermoregulation and acoustics into a single word the beekeeper can act on, sent alongside the raw numbers.

Configuration & Calibration

Configuration steps

  • Set HX_SCALE and the tare from calibration with a known weight; set T_CAL to the temperature at tare and K_T from the observed day/night drift of the empty scale.
  • Adjust the brood-temperature thresholds to your bee subspecies and climate; 34–35 Β°C is typical but local strains vary.
  • Tune the acoustic ratio multiplier (default 1.4Γ—) after watching a real colony, since band energy depends on mic placement.
  • Choose the LoRa frequency legal in your region and the sampling interval (15–30 min captures the daily curve).

Calibration procedure

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

  1. Weight

    Tare empty, apply a known reference weight, and set HX_SCALE so the reading matches. Verify linearity with a second known weight.

  2. Temperature drift

    Leave the empty (or fixed-load) scale running through a full day and night; the swing in the reading against ambient gives K_T, the compensation coefficient.

  3. Acoustic baseline

    Record the band ratio over several days of a known-queenright colony to establish ratioBase before trusting swarm/queenless flags.

Network Architecture & Connectivity

Beehive Health Monitor β€” network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsHive nodeESP32 + LoRaOther hivessame siteLoRa 433/868Apiary gatewayLoRa β†’ MQTTMQTT 1883Broker + dashboardper-hive season historyDashboardhive gridPhoneinspection alerts
Beehive Health Monitor β€” network topology

Communication protocol

Compact JSON travels over LoRa (SF10) every 15–30 minutes. The weight trend and the fused verdict are the priority fields; raw audio is never transmitted β€” only the couple of band-energy features computed on-board β€” which keeps the packet tiny and the battery alive.

Topic / endpointDirectionPayload
apiary/hive/1/datanode β†’ brokerweight, trend, brood T/RH, ratio
apiary/hive/1/alertnode β†’ brokerbrood-cooling / weight / swarm
apiary/hive/1/statusnode β†’ brokerbattery, RSSI, uptime

Message contract between the device and the broker.

Cloud platform configuration

The gateway publishes to MQTT; a dashboard keeps a per-hive history of weight, brood temperature and acoustic features across the whole season, turning many colonies into one comparable record.

Dashboard setup

A grid of hive tiles coloured by verdict, each expanding to its weight, temperature and acoustic history β€” the beekeeper's route-planning view of which colonies to visit first.

Mobile app integration

Push alerts name the hive and the reason to open it: brood cooling, a sudden weight loss, or a rising swarm signature.

Security considerations

  • A per-hive key and rolling counter stop a stray identical node from injecting false data into a neighbour's record.
  • Authenticate the broker so only the beekeeper's dashboard reads the apiary data.
  • Alert on a hive going silent so a dead node is not mistaken for a healthy, quiet colony.

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
Add a known weight to the platformReading increases by that weight within tolerance after compensation
Warm the load cell (e.g. sun/heat) with fixed loadCompensated weight stays roughly constant; uncompensated would drift
Cool the brood probe below 32 Β°CVerdict flags brood cooling
Play a rising-frequency tone near the micAcoustic ratio increases; swarm-watch can trigger above baseline
Range-test the LoRa link across the apiaryPackets received at the base with usable RSSI
Run a solar day/night cycleBattery recovers by day; RTC-stored trend persists across sleeps

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

Expected output

The per-hive dashboard shows a weight curve (daily wobble on a rising or falling trend), brood temperature against ambient, the acoustic ratio, and the current verdict word.

jsonhive-packet.json
{
  "hive": 1,
  "w": 38.42,
  "trend": 37.9,
  "broodT": 34.8,
  "rh": 58,
  "ambT": 22.1,
  "ratio": 0.91,
  "v": "OK"
}

A healthy colony in a flow shows the trend climbing day over day with brood temperature pinned near 35 Β°C and a stable acoustic ratio; a "CRITICAL" verdict pairs a cold brood nest with a weight step-down or a rising acoustic ratio.

A LoRa radio transceiver module
A LoRa radio carries each hive's weight, temperature and acoustic verdict back to the beekeeper across the field. Photograph sourced from Wikimedia Commons β€” LoRa module.jpg. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Weight wanders with the time of day

Likely cause. Load-cell temperature drift not compensated

Fix. Measure K_T from the empty-scale day/night swing and apply the compensation; keep the cell shaded

Weight reading is noisy or jumps

Likely cause. Long HX711 leads, uneven load, or a tilted hive

Fix. Shorten and shield the leads; level the platform; average more samples per read

Brood temperature reads oddly low

Likely cause. Probe propolised over or displaced to the hive edge

Fix. Use the vented cage; reposition the probe near the brood-nest centre

Acoustic ratio is meaningless/erratic

Likely cause. Mic hearing wind, or picking up enclosure vibration

Fix. Shield the mic from wind; couple it to the hive body; average several captures

Battery dies mid-season

Likely cause. Sampling too often or audio capture too long

Fix. Lengthen the interval; shorten the audio block; clean the solar panel

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 reads; the HX711 settling and the audio capture dominate awake time, so keep both as short as accuracy allows.
  • Transmit acoustic features, never raw audio β€” a few band energies instead of kilobytes of samples.
  • Persist trend and baselines in RTC memory so the multi-day story survives sleep without re-learning.
  • Average enough weight samples to beat load-cell noise, but no more; each extra sample is awake-time and battery.
  • 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

  • Wear appropriate protection when installing or servicing sensors; a monitored hive is still a defensive colony.
  • Keep the lithium battery and charger in the sealed enclosure, away from moisture and hive debris.
  • The monitor guides inspections; it does not replace the beekeeper's judgement or routine disease checks (e.g. for mites).
  • Secure cables so bees cannot be trapped and the colony cannot propolise the electronics into a heat trap.
  • 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-tare and spot-check the scale against a known weight periodically; load cells drift over a season.
  • Free the brood probe of propolis and confirm it still sits in the brood nest.
  • Clean the solar panel and check the mic's acoustic path is not blocked by wax or debris.
  • Re-learn the acoustic baseline after re-queening or moving the hive, since the colony's normal changes.
  • 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 bee-counter at the entrance to correlate forager traffic with the weight rhythm.
  • Run a small on-device classifier on the audio features for queenless/pre-swarm detection instead of thresholds.
  • Add a Varroa-drop tray sensor to fold mite load into the health verdict.
  • Aggregate many hives' weight trends into a live nectar-flow map for a region.
  • 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

Can it really tell me the queen is failing without opening the hive?

Not with certainty, but a colony that stops holding its brood nest near 35 Β°C has usually lost the queen or the population to keep brood warm. Combined with weight and sound, it is a strong, early flag to inspect.

Why weigh the hive at all?

Weight is the single richest signal: its daily wobble shows foraging, its slow trend is the honey flow, and a sudden step down can mean a swarm or robbing. It is the backbone of remote hive monitoring.

Do you transmit recordings of the bees?

No. The device computes a couple of band-energy features on-board and sends only those numbers β€” cheap over LoRa and privacy-free.

Why does the weight need temperature compensation?

Load cells drift with temperature. Without correction, the sun warming the scale each afternoon would look like the colony gaining and losing a kilo every day.

How long does it run in the field?

A small solar panel and one 18650 cover a season, because the device sleeps between reads and never transmits raw audio.

References & Learning Resources

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

  1. Honeybee brood-nest thermoregulation β€” research overviewReference
  2. HX711 24-bit ADC for load cells (datasheet)Avia Semiconductor
  3. INMP441 IΒ²S MEMS microphone (datasheet)TDK InvenSense
  4. Acoustic monitoring of honeybee colonies β€” literatureReference
  5. Precision beekeeping / hive scales β€” overviewReference