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.
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
| Setting | How it is used |
|---|---|
| Hobby and sideline beekeeping | A 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 apiaries | Hundreds of hives across many sites, where a scale on each colony turns hive management into a prioritised route rather than a blind round. |
| Pollination services | Growers renting hives for pollination can verify colony strength and activity objectively during the contract. |
| Research and conservation | Long-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
| Attribute | Value |
|---|---|
| Difficulty level | Intermediate |
| Estimated completion time | 12β18 hours |
| Indicative build cost | βΉ3,800 β βΉ5,200 |
| Primary discipline | Agriculture |
| Reference platform | ESP32 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.
| 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 |
| 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 SPS | 1 | βΉ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 heater | 1 | βΉ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 ID | 1 | βΉ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 output | 1 | βΉ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β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 |
| 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 kg | 1 | βΉ1,100 |
| Vented probe cage | Protects the SHT31 in the brood box from propolis while letting air through | 1 | βΉ90 |
| Weatherproof enclosure | IP65 for the electronics, mounted on or beside the hive stand | 1 | βΉ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
| 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 |
| 5 kg load cell + HX711 24-bit ADC | Strain-gauge bridge, 1.0 mV/V output, HX711 128Γ gain, 10/80 SPS | 2.6β5.5 V | 2-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 heater | 2.4β5.5 V | IΒ²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 ID | 3.0β5.5 V | 1-Wire (multi-drop) | Datasheet |
| INMP441 IΒ²S MEMS microphone | 61 dB SNR, β26 dBFS sensitivity, 60 Hzβ15 kHz, 24-bit IΒ²S output | 1.8β3.3 V | IΒ²S | 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. |
| 5 kg load cell + HX711 24-bit ADC | 2.6β5.5 V | 1.5 | Mechanical mounting dominates accuracy β bolt it to a rigid plate, not plastic. |
| 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. |
| DS18B20 waterproof temperature probe | 3.0β5.5 V | 1.5 | Dozens can share one GPIO β you address them by ROM code. |
| INMP441 IΒ²S MEMS microphone | 1.8β3.3 V | 1.4 | Digital output means no analogue noise pickup β far better than an MAX9814 for keyword spotting. |
| 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 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.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 |
| HX711 0.7.x | Bit-banged 24-bit ADC read with tare and calibration factor. | Library Manager β "HX711" by Bogdan Necula |
| Adafruit Unified Sensor 1.1.x | Common sensor event abstraction; a dependency of most Adafruit drivers. | Library Manager β "Adafruit Unified Sensor" |
| OneWire + DallasTemperature 2.3.x / 3.9.x | Bus enumeration and conversion commands for DS18B20 probes. | Library Manager β "DallasTemperature" (pulls OneWire) |
| 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 |
|---|---|---|---|
| HX711 (load cell) | DT/SCK | GPIO 16/4 | Weight ADC (24-bit) |
| SHT31 | SDA/SCL | GPIO 21/22 | Brood temp + humidity (IΒ²C) |
| DS18B20 | DQ | GPIO 17 | Ambient temp (load-cell compensation) |
| INMP441 mic | SD/WS/SCK | GPIO 33/25/32 | IΒ²S hive audio |
| LoRa SX1276 | SCK/MISO/MOSI | GPIO 18/19/23 | SPI radio bus |
| LoRa SX1276 | NSS/RST/DIO0 | GPIO 5/14/2 | Chip-select, reset, 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
- 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.
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
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
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
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
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
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.
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 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.
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.
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.
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.
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.
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.inostruct 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.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.
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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()
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.
Weight
Tare empty, apply a known reference weight, and set HX_SCALE so the reading matches. Verify linearity with a second known weight.
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.
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
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 / endpoint | Direction | Payload |
|---|---|---|
apiary/hive/1/data | node β broker | weight, trend, brood T/RH, ratio |
apiary/hive/1/alert | node β broker | brood-cooling / weight / swarm |
apiary/hive/1/status | node β broker | battery, 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.
| Test | What you should see |
|---|---|
| Add a known weight to the platform | Reading increases by that weight within tolerance after compensation |
| Warm the load cell (e.g. sun/heat) with fixed load | Compensated weight stays roughly constant; uncompensated would drift |
| Cool the brood probe below 32 Β°C | Verdict flags brood cooling |
| Play a rising-frequency tone near the mic | Acoustic ratio increases; swarm-watch can trigger above baseline |
| Range-test the LoRa link across the apiary | Packets received at the base with usable RSSI |
| Run a solar day/night cycle | Battery 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.
{
"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.
Troubleshooting: Common Errors & Fixes
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 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
- 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
References & Learning Resources
These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.
- Honeybee brood-nest thermoregulation β research overviewReference
- HX711 24-bit ADC for load cells (datasheet)Avia Semiconductor
- INMP441 IΒ²S MEMS microphone (datasheet)TDK InvenSense
- Acoustic monitoring of honeybee colonies β literatureReference
- Precision beekeeping / hive scales β overviewReference